Skip to main content

rustc_hir_analysis/check/
wfcheck.rs

1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::{ExternAbi, ScalableElt};
6use rustc_ast as ast;
7use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err};
10use rustc_hir as hir;
11use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution};
12use rustc_hir::def::{DefKind, Res};
13use rustc_hir::def_id::{DefId, LocalDefId};
14use rustc_hir::lang_items::LangItem;
15use rustc_hir::{AmbigArg, ItemKind, find_attr};
16use rustc_infer::infer::outlives::env::OutlivesEnvironment;
17use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
18use rustc_lint_defs::builtin::SHADOWING_SUPERTRAIT_ITEMS;
19use rustc_macros::Diagnostic;
20use rustc_middle::mir::interpret::ErrorHandled;
21use rustc_middle::traits::solve::NoSolution;
22use rustc_middle::ty::trait_def::TraitSpecializationKind;
23use rustc_middle::ty::{
24    self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
25    TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
26    Upcast,
27};
28use rustc_middle::{bug, span_bug};
29use rustc_session::parse::feature_err;
30use rustc_span::{DUMMY_SP, Span, sym};
31use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
32use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
33use rustc_trait_selection::traits::misc::{
34    ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
35};
36use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
37use rustc_trait_selection::traits::{
38    self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
39    WellFormedLoc,
40};
41use tracing::{debug, instrument};
42
43use super::compare_eii::compare_eii_function_types;
44use crate::autoderef::Autoderef;
45use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
46use crate::errors;
47use crate::errors::InvalidReceiverTyHint;
48
49pub(super) struct WfCheckingCtxt<'a, 'tcx> {
50    pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
51    body_def_id: LocalDefId,
52    param_env: ty::ParamEnv<'tcx>,
53}
54impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
55    type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
56    fn deref(&self) -> &Self::Target {
57        &self.ocx
58    }
59}
60
61impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
62    fn tcx(&self) -> TyCtxt<'tcx> {
63        self.ocx.infcx.tcx
64    }
65
66    // Convenience function to normalize during wfcheck. This performs
67    // `ObligationCtxt::normalize`, but provides a nice `ObligationCauseCode`.
68    fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
69    where
70        T: TypeFoldable<TyCtxt<'tcx>>,
71    {
72        self.ocx.normalize(
73            &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
74            self.param_env,
75            value,
76        )
77    }
78
79    /// Convenience function to *deeply* normalize during wfcheck. In the old solver,
80    /// this just dispatches to [`WfCheckingCtxt::normalize`], but in the new solver
81    /// this calls `deeply_normalize` and reports errors if they are encountered.
82    ///
83    /// This function should be called in favor of `normalize` in cases where we will
84    /// then check the well-formedness of the type, since we only use the normalized
85    /// signature types for implied bounds when checking regions.
86    // FIXME(-Znext-solver): This should be removed when we compute implied outlives
87    // bounds using the unnormalized signature of the function we're checking.
88    pub(super) fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
89    where
90        T: TypeFoldable<TyCtxt<'tcx>>,
91    {
92        if self.infcx.next_trait_solver() {
93            match self.ocx.deeply_normalize(
94                &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
95                self.param_env,
96                value.clone(),
97            ) {
98                Ok(value) => value,
99                Err(errors) => {
100                    self.infcx.err_ctxt().report_fulfillment_errors(errors);
101                    value
102                }
103            }
104        } else {
105            self.normalize(span, loc, value)
106        }
107    }
108
109    pub(super) fn register_wf_obligation(
110        &self,
111        span: Span,
112        loc: Option<WellFormedLoc>,
113        term: ty::Term<'tcx>,
114    ) {
115        let cause = traits::ObligationCause::new(
116            span,
117            self.body_def_id,
118            ObligationCauseCode::WellFormed(loc),
119        );
120        self.ocx.register_obligation(Obligation::new(
121            self.tcx(),
122            cause,
123            self.param_env,
124            ty::ClauseKind::WellFormed(term),
125        ));
126    }
127}
128
129pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
130    tcx: TyCtxt<'tcx>,
131    body_def_id: LocalDefId,
132    f: F,
133) -> Result<(), ErrorGuaranteed>
134where
135    F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
136{
137    let param_env = tcx.param_env(body_def_id);
138    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
139    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
140
141    let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
142
143    if !tcx.features().trivial_bounds() {
144        wfcx.check_false_global_bounds()
145    }
146    f(&mut wfcx)?;
147
148    let errors = wfcx.evaluate_obligations_error_on_ambiguity();
149    if !errors.is_empty() {
150        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
151    }
152
153    let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
154    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:154",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(154u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["assumed_wf_types"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&assumed_wf_types)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?assumed_wf_types);
155
156    let infcx_compat = infcx.fork();
157
158    // We specifically want to *disable* the implied bounds hack, first,
159    // so we can detect when failures are due to bevy's implied bounds.
160    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
161        &infcx,
162        body_def_id,
163        param_env,
164        assumed_wf_types.iter().copied(),
165        true,
166    );
167
168    lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
169
170    let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
171    if errors.is_empty() {
172        return Ok(());
173    }
174
175    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
176        &infcx_compat,
177        body_def_id,
178        param_env,
179        assumed_wf_types,
180        // Don't *disable* the implied bounds hack; though this will only apply
181        // the implied bounds hack if this contains `bevy_ecs`'s `ParamSet` type.
182        false,
183    );
184    let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
185    if errors_compat.is_empty() {
186        // FIXME: Once we fix bevy, this would be the place to insert a warning
187        // to upgrade bevy.
188        Ok(())
189    } else {
190        Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
191    }
192}
193
194pub(super) fn check_well_formed(
195    tcx: TyCtxt<'_>,
196    def_id: LocalDefId,
197) -> Result<(), ErrorGuaranteed> {
198    let mut res = crate::check::check::check_item_type(tcx, def_id);
199
200    for param in &tcx.generics_of(def_id).own_params {
201        res = res.and(check_param_wf(tcx, param));
202    }
203
204    res
205}
206
207/// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
208/// well-formed, meaning that they do not require any constraints not declared in the struct
209/// definition itself. For example, this definition would be illegal:
210///
211/// ```rust
212/// struct StaticRef<T> { x: &'static T }
213/// ```
214///
215/// because the type did not declare that `T: 'static`.
216///
217/// We do this check as a pre-pass before checking fn bodies because if these constraints are
218/// not included it frequently leads to confusing errors in fn bodies. So it's better to check
219/// the types first.
220#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_item",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(220u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let def_id = item.owner_id.def_id;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:227",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(227u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item.owner_id",
                                                    "item.name"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&item.owner_id)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&tcx.def_path_str(def_id))
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            match item.kind {
                hir::ItemKind::Impl(ref impl_) => {
                    crate::impl_wf_check::check_impl_wf(tcx, def_id,
                            impl_.of_trait.is_some())?;
                    let mut res = Ok(());
                    if let Some(of_trait) = impl_.of_trait {
                        let header = tcx.impl_trait_header(def_id);
                        let is_auto =
                            tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
                        if let (hir::Defaultness::Default { .. }, true) =
                                (of_trait.defaultness, is_auto) {
                            let sp = of_trait.trait_ref.path.span;
                            res =
                                Err(tcx.dcx().struct_span_err(sp,
                                                    "impls of auto traits cannot be default").with_span_labels(of_trait.defaultness_span,
                                                "default because of this").with_span_label(sp,
                                            "auto trait").emit());
                        }
                        match header.polarity {
                            ty::ImplPolarity::Positive => {
                                res = res.and(check_impl(tcx, item, impl_));
                            }
                            ty::ImplPolarity::Negative => {
                                let ast::ImplPolarity::Negative(span) =
                                    of_trait.polarity else {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("impl_polarity query disagrees with impl\'s polarity in HIR"));
                                    };
                                if let hir::Defaultness::Default { .. } =
                                        of_trait.defaultness {
                                    let mut spans =
                                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [span]));
                                    spans.extend(of_trait.defaultness_span);
                                    res =
                                        Err({
                                                    tcx.dcx().struct_span_err(spans,
                                                            ::alloc::__export::must_use({
                                                                    ::alloc::fmt::format(format_args!("negative impls cannot be default impls"))
                                                                })).with_code(E0750)
                                                }.emit());
                                }
                            }
                            ty::ImplPolarity::Reservation => {}
                        }
                    } else { res = res.and(check_impl(tcx, item, impl_)); }
                    res
                }
                hir::ItemKind::Fn { sig, .. } =>
                    check_item_fn(tcx, def_id, sig.decl),
                hir::ItemKind::Struct(..) =>
                    check_type_defn(tcx, item, false),
                hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
                hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
                hir::ItemKind::Trait(..) => check_trait(tcx, item),
                hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
                _ => Ok(()),
            }
        }
    }
}#[instrument(skip(tcx), level = "debug")]
221pub(super) fn check_item<'tcx>(
222    tcx: TyCtxt<'tcx>,
223    item: &'tcx hir::Item<'tcx>,
224) -> Result<(), ErrorGuaranteed> {
225    let def_id = item.owner_id.def_id;
226
227    debug!(
228        ?item.owner_id,
229        item.name = ? tcx.def_path_str(def_id)
230    );
231
232    match item.kind {
233        // Right now we check that every default trait implementation
234        // has an implementation of itself. Basically, a case like:
235        //
236        //     impl Trait for T {}
237        //
238        // has a requirement of `T: Trait` which was required for default
239        // method implementations. Although this could be improved now that
240        // there's a better infrastructure in place for this, it's being left
241        // for a follow-up work.
242        //
243        // Since there's such a requirement, we need to check *just* positive
244        // implementations, otherwise things like:
245        //
246        //     impl !Send for T {}
247        //
248        // won't be allowed unless there's an *explicit* implementation of `Send`
249        // for `T`
250        hir::ItemKind::Impl(ref impl_) => {
251            crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
252            let mut res = Ok(());
253            if let Some(of_trait) = impl_.of_trait {
254                let header = tcx.impl_trait_header(def_id);
255                let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
256                if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
257                    let sp = of_trait.trait_ref.path.span;
258                    res = Err(tcx
259                        .dcx()
260                        .struct_span_err(sp, "impls of auto traits cannot be default")
261                        .with_span_labels(of_trait.defaultness_span, "default because of this")
262                        .with_span_label(sp, "auto trait")
263                        .emit());
264                }
265                match header.polarity {
266                    ty::ImplPolarity::Positive => {
267                        res = res.and(check_impl(tcx, item, impl_));
268                    }
269                    ty::ImplPolarity::Negative => {
270                        let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
271                            bug!("impl_polarity query disagrees with impl's polarity in HIR");
272                        };
273                        // FIXME(#27579): what amount of WF checking do we need for neg impls?
274                        if let hir::Defaultness::Default { .. } = of_trait.defaultness {
275                            let mut spans = vec![span];
276                            spans.extend(of_trait.defaultness_span);
277                            res = Err(struct_span_code_err!(
278                                tcx.dcx(),
279                                spans,
280                                E0750,
281                                "negative impls cannot be default impls"
282                            )
283                            .emit());
284                        }
285                    }
286                    ty::ImplPolarity::Reservation => {
287                        // FIXME: what amount of WF checking do we need for reservation impls?
288                    }
289                }
290            } else {
291                res = res.and(check_impl(tcx, item, impl_));
292            }
293            res
294        }
295        hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
296        hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
297        hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
298        hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
299        hir::ItemKind::Trait(..) => check_trait(tcx, item),
300        hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
301        _ => Ok(()),
302    }
303}
304
305pub(super) fn check_foreign_item<'tcx>(
306    tcx: TyCtxt<'tcx>,
307    item: &'tcx hir::ForeignItem<'tcx>,
308) -> Result<(), ErrorGuaranteed> {
309    let def_id = item.owner_id.def_id;
310
311    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:311",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(311u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["item.owner_id",
                                        "item.name"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&item.owner_id)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&tcx.def_path_str(def_id))
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(
312        ?item.owner_id,
313        item.name = ? tcx.def_path_str(def_id)
314    );
315
316    match item.kind {
317        hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
318        hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
319    }
320}
321
322pub(crate) fn check_trait_item<'tcx>(
323    tcx: TyCtxt<'tcx>,
324    def_id: LocalDefId,
325) -> Result<(), ErrorGuaranteed> {
326    // Check that an item definition in a subtrait is shadowing a supertrait item.
327    lint_item_shadowing_supertrait_item(tcx, def_id);
328
329    let mut res = Ok(());
330
331    if tcx.def_kind(def_id) == DefKind::AssocFn {
332        for &assoc_ty_def_id in
333            tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
334        {
335            res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
336        }
337    }
338    res
339}
340
341/// Require that the user writes where clauses on GATs for the implicit
342/// outlives bounds involving trait parameters in trait functions and
343/// lifetimes passed as GAT args. See `self-outlives-lint` test.
344///
345/// We use the following trait as an example throughout this function:
346/// ```rust,ignore (this code fails due to this lint)
347/// trait IntoIter {
348///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
349///     type Item<'a>;
350///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
351/// }
352/// ```
353fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
354    // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
355    let mut required_bounds_by_item = FxIndexMap::default();
356    let associated_items = tcx.associated_items(trait_def_id);
357
358    // Loop over all GATs together, because if this lint suggests adding a where-clause bound
359    // to one GAT, it might then require us to an additional bound on another GAT.
360    // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
361    // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
362    // those GATs.
363    loop {
364        let mut should_continue = false;
365        for gat_item in associated_items.in_definition_order() {
366            let gat_def_id = gat_item.def_id.expect_local();
367            let gat_item = tcx.associated_item(gat_def_id);
368            // If this item is not an assoc ty, or has no args, then it's not a GAT
369            if !gat_item.is_type() {
370                continue;
371            }
372            let gat_generics = tcx.generics_of(gat_def_id);
373            // FIXME(jackh726): we can also warn in the more general case
374            if gat_generics.is_own_empty() {
375                continue;
376            }
377
378            // Gather the bounds with which all other items inside of this trait constrain the GAT.
379            // This is calculated by taking the intersection of the bounds that each item
380            // constrains the GAT with individually.
381            let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
382            for item in associated_items.in_definition_order() {
383                let item_def_id = item.def_id.expect_local();
384                // Skip our own GAT, since it does not constrain itself at all.
385                if item_def_id == gat_def_id {
386                    continue;
387                }
388
389                let param_env = tcx.param_env(item_def_id);
390
391                let item_required_bounds = match tcx.associated_item(item_def_id).kind {
392                    // In our example, this corresponds to `into_iter` method
393                    ty::AssocKind::Fn { .. } => {
394                        // For methods, we check the function signature's return type for any GATs
395                        // to constrain. In the `into_iter` case, we see that the return type
396                        // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
397                        let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
398                            item_def_id.to_def_id(),
399                            tcx.fn_sig(item_def_id).instantiate_identity(),
400                        );
401                        gather_gat_bounds(
402                            tcx,
403                            param_env,
404                            item_def_id,
405                            sig.inputs_and_output,
406                            // We also assume that all of the function signature's parameter types
407                            // are well formed.
408                            &sig.inputs().iter().copied().collect(),
409                            gat_def_id,
410                            gat_generics,
411                        )
412                    }
413                    // In our example, this corresponds to the `Iter` and `Item` associated types
414                    ty::AssocKind::Type { .. } => {
415                        // If our associated item is a GAT with missing bounds, add them to
416                        // the param-env here. This allows this GAT to propagate missing bounds
417                        // to other GATs.
418                        let param_env = augment_param_env(
419                            tcx,
420                            param_env,
421                            required_bounds_by_item.get(&item_def_id),
422                        );
423                        gather_gat_bounds(
424                            tcx,
425                            param_env,
426                            item_def_id,
427                            tcx.explicit_item_bounds(item_def_id)
428                                .iter_identity_copied()
429                                .collect::<Vec<_>>(),
430                            &FxIndexSet::default(),
431                            gat_def_id,
432                            gat_generics,
433                        )
434                    }
435                    ty::AssocKind::Const { .. } => None,
436                };
437
438                if let Some(item_required_bounds) = item_required_bounds {
439                    // Take the intersection of the required bounds for this GAT, and
440                    // the item_required_bounds which are the ones implied by just
441                    // this item alone.
442                    // This is why we use an Option<_>, since we need to distinguish
443                    // the empty set of bounds from the _uninitialized_ set of bounds.
444                    if let Some(new_required_bounds) = &mut new_required_bounds {
445                        new_required_bounds.retain(|b| item_required_bounds.contains(b));
446                    } else {
447                        new_required_bounds = Some(item_required_bounds);
448                    }
449                }
450            }
451
452            if let Some(new_required_bounds) = new_required_bounds {
453                let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
454                if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
455                    // Iterate until our required_bounds no longer change
456                    // Since they changed here, we should continue the loop
457                    should_continue = true;
458                }
459            }
460        }
461        // We know that this loop will eventually halt, since we only set `should_continue` if the
462        // `required_bounds` for this item grows. Since we are not creating any new region or type
463        // variables, the set of all region and type bounds that we could ever insert are limited
464        // by the number of unique types and regions we observe in a given item.
465        if !should_continue {
466            break;
467        }
468    }
469
470    for (gat_def_id, required_bounds) in required_bounds_by_item {
471        // Don't suggest adding `Self: 'a` to a GAT that can't be named
472        if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
473            continue;
474        }
475
476        let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
477        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:477",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(477u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["required_bounds"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&required_bounds)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?required_bounds);
478        let param_env = tcx.param_env(gat_def_id);
479
480        let unsatisfied_bounds: Vec<_> = required_bounds
481            .into_iter()
482            .filter(|clause| match clause.kind().skip_binder() {
483                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
484                    !region_known_to_outlive(
485                        tcx,
486                        gat_def_id,
487                        param_env,
488                        &FxIndexSet::default(),
489                        a,
490                        b,
491                    )
492                }
493                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
494                    !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
495                }
496                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
497            })
498            .map(|clause| clause.to_string())
499            .collect();
500
501        if !unsatisfied_bounds.is_empty() {
502            let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
503            let suggestion = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}",
                gat_item_hir.generics.add_where_or_trailing_comma(),
                unsatisfied_bounds.join(", ")))
    })format!(
504                "{} {}",
505                gat_item_hir.generics.add_where_or_trailing_comma(),
506                unsatisfied_bounds.join(", "),
507            );
508            let bound =
509                if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
510            tcx.dcx()
511                .struct_span_err(
512                    gat_item_hir.span,
513                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing required bound{0} on `{1}`",
                plural, gat_item_hir.ident))
    })format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
514                )
515                .with_span_suggestion(
516                    gat_item_hir.generics.tail_span_for_predicate_suggestion(),
517                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add the required where clause{0}",
                plural))
    })format!("add the required where clause{plural}"),
518                    suggestion,
519                    Applicability::MachineApplicable,
520                )
521                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
                bound))
    })format!(
522                    "{bound} currently required to ensure that impls have maximum flexibility"
523                ))
524                .with_note(
525                    "we are soliciting feedback, see issue #87479 \
526                     <https://github.com/rust-lang/rust/issues/87479> for more information",
527                )
528                .emit();
529        }
530    }
531}
532
533/// Add a new set of predicates to the caller_bounds of an existing param_env.
534fn augment_param_env<'tcx>(
535    tcx: TyCtxt<'tcx>,
536    param_env: ty::ParamEnv<'tcx>,
537    new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
538) -> ty::ParamEnv<'tcx> {
539    let Some(new_predicates) = new_predicates else {
540        return param_env;
541    };
542
543    if new_predicates.is_empty() {
544        return param_env;
545    }
546
547    let bounds = tcx.mk_clauses_from_iter(
548        param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
549    );
550    // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
551    // i.e. traits::normalize_param_env_or_error
552    ty::ParamEnv::new(bounds)
553}
554
555/// We use the following trait as an example throughout this function.
556/// Specifically, let's assume that `to_check` here is the return type
557/// of `into_iter`, and the GAT we are checking this for is `Iter`.
558/// ```rust,ignore (this code fails due to this lint)
559/// trait IntoIter {
560///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
561///     type Item<'a>;
562///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
563/// }
564/// ```
565fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
566    tcx: TyCtxt<'tcx>,
567    param_env: ty::ParamEnv<'tcx>,
568    item_def_id: LocalDefId,
569    to_check: T,
570    wf_tys: &FxIndexSet<Ty<'tcx>>,
571    gat_def_id: LocalDefId,
572    gat_generics: &'tcx ty::Generics,
573) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
574    // The bounds we that we would require from `to_check`
575    let mut bounds = FxIndexSet::default();
576
577    let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
578
579    // If both regions and types are empty, then this GAT isn't in the
580    // set of types we are checking, and we shouldn't try to do clause analysis
581    // (particularly, doing so would end up with an empty set of clauses,
582    // since the current method would require none, and we take the
583    // intersection of requirements of all methods)
584    if types.is_empty() && regions.is_empty() {
585        return None;
586    }
587
588    for (region_a, region_a_idx) in &regions {
589        // Ignore `'static` lifetimes for the purpose of this lint: it's
590        // because we know it outlives everything and so doesn't give meaningful
591        // clues. Also ignore `ReError`, to avoid knock-down errors.
592        if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
593            continue;
594        }
595        // For each region argument (e.g., `'a` in our example), check for a
596        // relationship to the type arguments (e.g., `Self`). If there is an
597        // outlives relationship (`Self: 'a`), then we want to ensure that is
598        // reflected in a where clause on the GAT itself.
599        for (ty, ty_idx) in &types {
600            // In our example, requires that `Self: 'a`
601            if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
602                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:602",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(602u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["ty_idx",
                                        "region_a_idx"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&ty_idx) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&region_a_idx)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?ty_idx, ?region_a_idx);
603                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:603",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(603u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
                                                    ty, region_a) as &dyn Value))])
            });
    } else { ; }
};debug!("required clause: {ty} must outlive {region_a}");
604                // Translate into the generic parameters of the GAT. In
605                // our example, the type was `Self`, which will also be
606                // `Self` in the GAT.
607                let ty_param = gat_generics.param_at(*ty_idx, tcx);
608                let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
609                // Same for the region. In our example, 'a corresponds
610                // to the 'me parameter.
611                let region_param = gat_generics.param_at(*region_a_idx, tcx);
612                let region_param = ty::Region::new_early_param(
613                    tcx,
614                    ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
615                );
616                // The predicate we expect to see. (In our example,
617                // `Self: 'me`.)
618                bounds.insert(
619                    ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
620                        .upcast(tcx),
621                );
622            }
623        }
624
625        // For each region argument (e.g., `'a` in our example), also check for a
626        // relationship to the other region arguments. If there is an outlives
627        // relationship, then we want to ensure that is reflected in the where clause
628        // on the GAT itself.
629        for (region_b, region_b_idx) in &regions {
630            // Again, skip `'static` because it outlives everything. Also, we trivially
631            // know that a region outlives itself. Also ignore `ReError`, to avoid
632            // knock-down errors.
633            if #[allow(non_exhaustive_omitted_patterns)] match region_b.kind() {
    ty::ReStatic | ty::ReError(_) => true,
    _ => false,
}matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
634                continue;
635            }
636            if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
637                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:637",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(637u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["region_a_idx",
                                        "region_b_idx"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&region_a_idx)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&region_b_idx)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?region_a_idx, ?region_b_idx);
638                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:638",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(638u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
                                                    region_a, region_b) as &dyn Value))])
            });
    } else { ; }
};debug!("required clause: {region_a} must outlive {region_b}");
639                // Translate into the generic parameters of the GAT.
640                let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
641                let region_a_param = ty::Region::new_early_param(
642                    tcx,
643                    ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
644                );
645                // Same for the region.
646                let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
647                let region_b_param = ty::Region::new_early_param(
648                    tcx,
649                    ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
650                );
651                // The predicate we expect to see.
652                bounds.insert(
653                    ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
654                        region_a_param,
655                        region_b_param,
656                    ))
657                    .upcast(tcx),
658                );
659            }
660        }
661    }
662
663    Some(bounds)
664}
665
666/// Given a known `param_env` and a set of well formed types, can we prove that
667/// `ty` outlives `region`.
668fn ty_known_to_outlive<'tcx>(
669    tcx: TyCtxt<'tcx>,
670    id: LocalDefId,
671    param_env: ty::ParamEnv<'tcx>,
672    wf_tys: &FxIndexSet<Ty<'tcx>>,
673    ty: Ty<'tcx>,
674    region: ty::Region<'tcx>,
675) -> bool {
676    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
677        infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
678            sub_region: region,
679            sup_type: ty,
680            origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
681        });
682    })
683}
684
685/// Given a known `param_env` and a set of well formed types, can we prove that
686/// `region_a` outlives `region_b`
687fn region_known_to_outlive<'tcx>(
688    tcx: TyCtxt<'tcx>,
689    id: LocalDefId,
690    param_env: ty::ParamEnv<'tcx>,
691    wf_tys: &FxIndexSet<Ty<'tcx>>,
692    region_a: ty::Region<'tcx>,
693    region_b: ty::Region<'tcx>,
694) -> bool {
695    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
696        infcx.sub_regions(
697            SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
698            region_b,
699            region_a,
700        );
701    })
702}
703
704/// Given a known `param_env` and a set of well formed types, set up an
705/// `InferCtxt`, call the passed function (to e.g. set up region constraints
706/// to be tested), then resolve region and return errors
707fn test_region_obligations<'tcx>(
708    tcx: TyCtxt<'tcx>,
709    id: LocalDefId,
710    param_env: ty::ParamEnv<'tcx>,
711    wf_tys: &FxIndexSet<Ty<'tcx>>,
712    add_constraints: impl FnOnce(&InferCtxt<'tcx>),
713) -> bool {
714    // Unfortunately, we have to use a new `InferCtxt` each call, because
715    // region constraints get added and solved there and we need to test each
716    // call individually.
717    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
718
719    add_constraints(&infcx);
720
721    let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
722    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:722",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(722u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message", "errors"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("errors")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errors) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?errors, "errors");
723
724    // If we were able to prove that the type outlives the region without
725    // an error, it must be because of the implied or explicit bounds...
726    errors.is_empty()
727}
728
729/// TypeVisitor that looks for uses of GATs like
730/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
731/// the two vectors, `regions` and `types` (depending on their kind). For each
732/// parameter `Pi` also track the index `i`.
733struct GATArgsCollector<'tcx> {
734    gat: DefId,
735    // Which region appears and which parameter index its instantiated with
736    regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
737    // Which params appears and which parameter index its instantiated with
738    types: FxIndexSet<(Ty<'tcx>, usize)>,
739}
740
741impl<'tcx> GATArgsCollector<'tcx> {
742    fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
743        gat: DefId,
744        t: T,
745    ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
746        let mut visitor =
747            GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
748        t.visit_with(&mut visitor);
749        (visitor.regions, visitor.types)
750    }
751}
752
753impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
754    fn visit_ty(&mut self, t: Ty<'tcx>) {
755        match t.kind() {
756            ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
757                for (idx, arg) in p.args.iter().enumerate() {
758                    match arg.kind() {
759                        GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
760                            self.regions.insert((lt, idx));
761                        }
762                        GenericArgKind::Type(t) => {
763                            self.types.insert((t, idx));
764                        }
765                        _ => {}
766                    }
767                }
768            }
769            _ => {}
770        }
771        t.super_visit_with(self)
772    }
773}
774
775fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
776    let item_name = tcx.item_name(trait_item_def_id.to_def_id());
777    let trait_def_id = tcx.local_parent(trait_item_def_id);
778
779    let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
780        .skip(1)
781        .flat_map(|supertrait_def_id| {
782            tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
783        })
784        .collect();
785    if !shadowed.is_empty() {
786        let shadowee = if let [shadowed] = shadowed[..] {
787            errors::SupertraitItemShadowee::Labeled {
788                span: tcx.def_span(shadowed.def_id),
789                supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
790            }
791        } else {
792            let (traits, spans): (Vec<_>, Vec<_>) = shadowed
793                .iter()
794                .map(|item| {
795                    (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
796                })
797                .unzip();
798            errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
799        };
800
801        tcx.emit_node_span_lint(
802            SHADOWING_SUPERTRAIT_ITEMS,
803            tcx.local_def_id_to_hir_id(trait_item_def_id),
804            tcx.def_span(trait_item_def_id),
805            errors::SupertraitItemShadowing {
806                item: item_name,
807                subtrait: tcx.item_name(trait_def_id.to_def_id()),
808                shadowee,
809            },
810        );
811    }
812}
813
814fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
815    match param.kind {
816        // We currently only check wf of const params here.
817        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
818
819        // Const parameters are well formed if their type is structural match.
820        ty::GenericParamDefKind::Const { .. } => {
821            let ty = tcx.type_of(param.def_id).instantiate_identity();
822            let span = tcx.def_span(param.def_id);
823            let def_id = param.def_id.expect_local();
824
825            if tcx.features().adt_const_params() {
826                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
827                    wfcx.register_bound(
828                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
829                        wfcx.param_env,
830                        ty,
831                        tcx.require_lang_item(LangItem::ConstParamTy, span),
832                    );
833                    Ok(())
834                })
835            } else {
836                let span = || {
837                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
838                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
839                    else {
840                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
841                    };
842                    span
843                };
844                let mut diag = match ty.kind() {
845                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
846                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
847                        span(),
848                        "using function pointers as const generic parameters is forbidden",
849                    ),
850                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
851                        span(),
852                        "using raw pointers as const generic parameters is forbidden",
853                    ),
854                    _ => {
855                        // Avoid showing "{type error}" to users. See #118179.
856                        ty.error_reported()?;
857
858                        tcx.dcx().struct_span_err(
859                            span(),
860                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
                ty))
    })format!(
861                                "`{ty}` is forbidden as the type of a const generic parameter",
862                            ),
863                        )
864                    }
865                };
866
867                diag.note("the only supported types are integers, `bool`, and `char`");
868
869                let cause = ObligationCause::misc(span(), def_id);
870                let adt_const_params_feature_string =
871                    " more complex and user defined types".to_string();
872                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
873                    tcx,
874                    tcx.param_env(param.def_id),
875                    ty,
876                    cause,
877                ) {
878                    // Can never implement `ConstParamTy`, don't suggest anything.
879                    Err(
880                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
881                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
882                    ) => None,
883                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
884                        Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(adt_const_params_feature_string, sym::adt_const_params),
                (" references to implement the `ConstParamTy` trait".into(),
                    sym::unsized_const_params)]))vec![
885                            (adt_const_params_feature_string, sym::adt_const_params),
886                            (
887                                " references to implement the `ConstParamTy` trait".into(),
888                                sym::unsized_const_params,
889                            ),
890                        ])
891                    }
892                    // May be able to implement `ConstParamTy`. Only emit the feature help
893                    // if the type is local, since the user may be able to fix the local type.
894                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
895                        fn ty_is_local(ty: Ty<'_>) -> bool {
896                            match ty.kind() {
897                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
898                                // Arrays and slices use the inner type's `ConstParamTy`.
899                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
900                                // `&` references use the inner type's `ConstParamTy`.
901                                // `&mut` are not supported.
902                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
903                                // Say that a tuple is local if any of its components are local.
904                                // This is not strictly correct, but it's likely that the user can fix the local component.
905                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
906                                _ => false,
907                            }
908                        }
909
910                        ty_is_local(ty).then_some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(adt_const_params_feature_string, sym::adt_const_params)]))vec![(
911                            adt_const_params_feature_string,
912                            sym::adt_const_params,
913                        )])
914                    }
915                    // Implements `ConstParamTy`, suggest adding the feature to enable.
916                    Ok(..) => Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(adt_const_params_feature_string, sym::adt_const_params)]))vec![(adt_const_params_feature_string, sym::adt_const_params)]),
917                };
918                if let Some(features) = may_suggest_feature {
919                    tcx.disabled_nightly_features(&mut diag, features);
920                }
921
922                Err(diag.emit())
923            }
924        }
925    }
926}
927
928#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_associated_item",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(928u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let loc = Some(WellFormedLoc::Ty(def_id));
            enter_wf_checking_ctxt(tcx, def_id,
                |wfcx|
                    {
                        let item = tcx.associated_item(def_id);
                        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
                        let self_ty =
                            match item.container {
                                ty::AssocContainer::Trait => tcx.types.self_param,
                                ty::AssocContainer::InherentImpl |
                                    ty::AssocContainer::TraitImpl(_) => {
                                    tcx.type_of(item.container_id(tcx)).instantiate_identity()
                                }
                            };
                        let span = tcx.def_span(def_id);
                        match item.kind {
                            ty::AssocKind::Const { .. } => {
                                let ty = tcx.type_of(def_id).instantiate_identity();
                                let ty =
                                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                        ty);
                                wfcx.register_wf_obligation(span, loc, ty.into());
                                let has_value = item.defaultness(tcx).has_value();
                                if tcx.is_type_const(def_id) {
                                    check_type_const(wfcx, def_id, ty, has_value)?;
                                }
                                if has_value {
                                    let code = ObligationCauseCode::SizedConstOrStatic;
                                    wfcx.register_bound(ObligationCause::new(span, def_id,
                                            code), wfcx.param_env, ty,
                                        tcx.require_lang_item(LangItem::Sized, span));
                                }
                                Ok(())
                            }
                            ty::AssocKind::Fn { .. } => {
                                let sig = tcx.fn_sig(def_id).instantiate_identity();
                                let hir_sig =
                                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
                                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
                                check_method_receiver(wfcx, hir_sig, item, self_ty)
                            }
                            ty::AssocKind::Type { .. } => {
                                if let ty::AssocContainer::Trait = item.container {
                                    check_associated_type_bounds(wfcx, item, span)
                                }
                                if item.defaultness(tcx).has_value() {
                                    let ty = tcx.type_of(def_id).instantiate_identity();
                                    let ty =
                                        wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                            ty);
                                    wfcx.register_wf_obligation(span, loc, ty.into());
                                }
                                Ok(())
                            }
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
929pub(crate) fn check_associated_item(
930    tcx: TyCtxt<'_>,
931    def_id: LocalDefId,
932) -> Result<(), ErrorGuaranteed> {
933    let loc = Some(WellFormedLoc::Ty(def_id));
934    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
935        let item = tcx.associated_item(def_id);
936
937        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
938        // other `Foo` impls are incoherent.
939        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
940
941        let self_ty = match item.container {
942            ty::AssocContainer::Trait => tcx.types.self_param,
943            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
944                tcx.type_of(item.container_id(tcx)).instantiate_identity()
945            }
946        };
947
948        let span = tcx.def_span(def_id);
949
950        match item.kind {
951            ty::AssocKind::Const { .. } => {
952                let ty = tcx.type_of(def_id).instantiate_identity();
953                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
954                wfcx.register_wf_obligation(span, loc, ty.into());
955
956                let has_value = item.defaultness(tcx).has_value();
957                if tcx.is_type_const(def_id) {
958                    check_type_const(wfcx, def_id, ty, has_value)?;
959                }
960
961                if has_value {
962                    let code = ObligationCauseCode::SizedConstOrStatic;
963                    wfcx.register_bound(
964                        ObligationCause::new(span, def_id, code),
965                        wfcx.param_env,
966                        ty,
967                        tcx.require_lang_item(LangItem::Sized, span),
968                    );
969                }
970
971                Ok(())
972            }
973            ty::AssocKind::Fn { .. } => {
974                let sig = tcx.fn_sig(def_id).instantiate_identity();
975                let hir_sig =
976                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
977                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
978                check_method_receiver(wfcx, hir_sig, item, self_ty)
979            }
980            ty::AssocKind::Type { .. } => {
981                if let ty::AssocContainer::Trait = item.container {
982                    check_associated_type_bounds(wfcx, item, span)
983                }
984                if item.defaultness(tcx).has_value() {
985                    let ty = tcx.type_of(def_id).instantiate_identity();
986                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
987                    wfcx.register_wf_obligation(span, loc, ty.into());
988                }
989                Ok(())
990            }
991        }
992    })
993}
994
995/// In a type definition, we check that to ensure that the types of the fields are well-formed.
996fn check_type_defn<'tcx>(
997    tcx: TyCtxt<'tcx>,
998    item: &hir::Item<'tcx>,
999    all_sized: bool,
1000) -> Result<(), ErrorGuaranteed> {
1001    let _ = tcx.check_representability(item.owner_id.def_id);
1002    let adt_def = tcx.adt_def(item.owner_id);
1003
1004    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1005        let variants = adt_def.variants();
1006        let packed = adt_def.repr().packed();
1007
1008        for variant in variants.iter() {
1009            // All field types must be well-formed.
1010            for field in &variant.fields {
1011                if let Some(def_id) = field.value
1012                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1013                {
1014                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1015                    // be refactored to check the instantiate-ability of the code better.
1016                    if let Some(def_id) = def_id.as_local()
1017                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1018                        && let expr = &tcx.hir_body(anon.body).value
1019                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1020                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1021                    {
1022                        // Do not evaluate bare `const` params, as those would ICE and are only
1023                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1024                    } else {
1025                        // Evaluate the constant proactively, to emit an error if the constant has
1026                        // an unconditional error. We only do so if the const has no type params.
1027                        let _ = tcx.const_eval_poly(def_id);
1028                    }
1029                }
1030                let field_id = field.did.expect_local();
1031                let hir::FieldDef { ty: hir_ty, .. } =
1032                    tcx.hir_node_by_def_id(field_id).expect_field();
1033                let ty = wfcx.deeply_normalize(
1034                    hir_ty.span,
1035                    None,
1036                    tcx.type_of(field.did).instantiate_identity(),
1037                );
1038                wfcx.register_wf_obligation(
1039                    hir_ty.span,
1040                    Some(WellFormedLoc::Ty(field_id)),
1041                    ty.into(),
1042                );
1043
1044                if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Adt(def, _) if def.repr().scalable() => true,
    _ => false,
}matches!(ty.kind(), ty::Adt(def, _) if def.repr().scalable())
1045                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1046                {
1047                    // Scalable vectors can only be fields of structs if the type has a
1048                    // `rustc_scalable_vector` attribute w/out specifying an element count
1049                    tcx.dcx().span_err(
1050                        hir_ty.span,
1051                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1052                            "scalable vectors cannot be fields of a {}",
1053                            adt_def.variant_descr()
1054                        ),
1055                    );
1056                }
1057            }
1058
1059            // For DST, or when drop needs to copy things around, all
1060            // intermediate types must be sized.
1061            let needs_drop_copy = || {
1062                packed && {
1063                    let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1064                    let ty = tcx.erase_and_anonymize_regions(ty);
1065                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1066                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1067                }
1068            };
1069            // All fields (except for possibly the last) should be sized.
1070            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1071            let unsized_len = if all_sized { 0 } else { 1 };
1072            for (idx, field) in
1073                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1074            {
1075                let last = idx == variant.fields.len() - 1;
1076                let field_id = field.did.expect_local();
1077                let hir::FieldDef { ty: hir_ty, .. } =
1078                    tcx.hir_node_by_def_id(field_id).expect_field();
1079                let ty = wfcx.normalize(
1080                    hir_ty.span,
1081                    None,
1082                    tcx.type_of(field.did).instantiate_identity(),
1083                );
1084                wfcx.register_bound(
1085                    traits::ObligationCause::new(
1086                        hir_ty.span,
1087                        wfcx.body_def_id,
1088                        ObligationCauseCode::FieldSized {
1089                            adt_kind: match &item.kind {
1090                                ItemKind::Struct(..) => AdtKind::Struct,
1091                                ItemKind::Union(..) => AdtKind::Union,
1092                                ItemKind::Enum(..) => AdtKind::Enum,
1093                                kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
    format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1094                                    item.span,
1095                                    "should be wfchecking an ADT, got {kind:?}"
1096                                ),
1097                            },
1098                            span: hir_ty.span,
1099                            last,
1100                        },
1101                    ),
1102                    wfcx.param_env,
1103                    ty,
1104                    tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1105                );
1106            }
1107
1108            // Explicit `enum` discriminant values must const-evaluate successfully.
1109            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1110                match tcx.const_eval_poly(discr_def_id) {
1111                    Ok(_) => {}
1112                    Err(ErrorHandled::Reported(..)) => {}
1113                    Err(ErrorHandled::TooGeneric(sp)) => {
1114                        ::rustc_middle::util::bug::span_bug_fmt(sp,
    format_args!("enum variant discr was too generic to eval"))span_bug!(sp, "enum variant discr was too generic to eval")
1115                    }
1116                }
1117            }
1118        }
1119
1120        check_where_clauses(wfcx, item.owner_id.def_id);
1121        Ok(())
1122    })
1123}
1124
1125#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_trait",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1125u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1127",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1127u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item.owner_id"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&item.owner_id)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let def_id = item.owner_id.def_id;
            if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
                return Ok(());
            }
            let trait_def = tcx.trait_def(def_id);
            if trait_def.is_marker ||
                    #[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
                        {
                        TraitSpecializationKind::Marker => true,
                        _ => false,
                    } {
                for associated_def_id in &*tcx.associated_item_def_ids(def_id)
                    {
                    {
                            tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
                                        })).with_code(E0714)
                        }.emit();
                }
            }
            let res =
                enter_wf_checking_ctxt(tcx, def_id,
                    |wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
            if let hir::ItemKind::Trait(..) = item.kind {
                check_gat_where_clauses(tcx, item.owner_id.def_id);
            }
            res
        }
    }
}#[instrument(skip(tcx, item))]
1126fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1127    debug!(?item.owner_id);
1128
1129    let def_id = item.owner_id.def_id;
1130    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1131        // `PointeeSized` is removed during lowering.
1132        return Ok(());
1133    }
1134
1135    let trait_def = tcx.trait_def(def_id);
1136    if trait_def.is_marker
1137        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1138    {
1139        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1140            struct_span_code_err!(
1141                tcx.dcx(),
1142                tcx.def_span(*associated_def_id),
1143                E0714,
1144                "marker traits cannot have associated items",
1145            )
1146            .emit();
1147        }
1148    }
1149
1150    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1151        check_where_clauses(wfcx, def_id);
1152        Ok(())
1153    });
1154
1155    // Only check traits, don't check trait aliases
1156    if let hir::ItemKind::Trait(..) = item.kind {
1157        check_gat_where_clauses(tcx, item.owner_id.def_id);
1158    }
1159    res
1160}
1161
1162/// Checks all associated type defaults of trait `trait_def_id`.
1163///
1164/// Assuming the defaults are used, check that all predicates (bounds on the
1165/// assoc type and where clauses on the trait) hold.
1166fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1167    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1168
1169    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1169",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1169u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
                                                    bounds) as &dyn Value))])
            });
    } else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1170    let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1171        traits::wf::clause_obligations(
1172            wfcx.infcx,
1173            wfcx.param_env,
1174            wfcx.body_def_id,
1175            bound,
1176            bound_span,
1177        )
1178    });
1179
1180    wfcx.register_obligations(wf_obligations);
1181}
1182
1183fn check_item_fn(
1184    tcx: TyCtxt<'_>,
1185    def_id: LocalDefId,
1186    decl: &hir::FnDecl<'_>,
1187) -> Result<(), ErrorGuaranteed> {
1188    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1189        check_eiis(tcx, def_id);
1190
1191        let sig = tcx.fn_sig(def_id).instantiate_identity();
1192        check_fn_or_method(wfcx, sig, decl, def_id);
1193        Ok(())
1194    })
1195}
1196
1197fn check_eiis(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1198    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1199    // that was used to mark the implementation. This is a two step process.
1200    for EiiImpl { resolution, span, .. } in
1201        {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                            break 'done Some(impls);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1202    {
1203        let (foreign_item, name) = match resolution {
1204            EiiImplResolution::Macro(def_id) => {
1205                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1206                // signature that we'd like to compare the function we're currently checking with
1207                if let Some(foreign_item) =
1208                    {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(*def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                            foreign_item: t, .. })) => {
                            break 'done Some(*t);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1209                {
1210                    (foreign_item, tcx.item_name(*def_id))
1211                } else {
1212                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1213                    continue;
1214                }
1215            }
1216            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1217            EiiImplResolution::Error(_eg) => continue,
1218        };
1219
1220        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1221    }
1222}
1223
1224#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_static_item",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1224u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item_id", "ty",
                                                    "should_check_for_sync"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&should_check_for_sync
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            enter_wf_checking_ctxt(tcx, item_id,
                |wfcx|
                    {
                        let span = tcx.ty_span(item_id);
                        let loc = Some(WellFormedLoc::Ty(item_id));
                        let item_ty = wfcx.deeply_normalize(span, loc, ty);
                        let is_foreign_item = tcx.is_foreign_item(item_id);
                        let is_structurally_foreign_item =
                            ||
                                {
                                    let tail =
                                        tcx.struct_tail_raw(item_ty, &ObligationCause::dummy(),
                                            |ty| wfcx.deeply_normalize(span, loc, ty), || {});

                                    #[allow(non_exhaustive_omitted_patterns)]
                                    match tail.kind() { ty::Foreign(_) => true, _ => false, }
                                };
                        let forbid_unsized =
                            !(is_foreign_item && is_structurally_foreign_item());
                        wfcx.register_wf_obligation(span,
                            Some(WellFormedLoc::Ty(item_id)), item_ty.into());
                        if forbid_unsized {
                            let span = tcx.def_span(item_id);
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sized, span));
                        }
                        let should_check_for_sync =
                            should_check_for_sync && !is_foreign_item &&
                                    tcx.static_mutability(item_id.to_def_id()) ==
                                        Some(hir::Mutability::Not) &&
                                !tcx.is_thread_local_static(item_id.to_def_id());
                        if should_check_for_sync {
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SharedStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sync, span));
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
1225pub(crate) fn check_static_item<'tcx>(
1226    tcx: TyCtxt<'tcx>,
1227    item_id: LocalDefId,
1228    ty: Ty<'tcx>,
1229    should_check_for_sync: bool,
1230) -> Result<(), ErrorGuaranteed> {
1231    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1232        let span = tcx.ty_span(item_id);
1233        let loc = Some(WellFormedLoc::Ty(item_id));
1234        let item_ty = wfcx.deeply_normalize(span, loc, ty);
1235
1236        let is_foreign_item = tcx.is_foreign_item(item_id);
1237        let is_structurally_foreign_item = || {
1238            let tail = tcx.struct_tail_raw(
1239                item_ty,
1240                &ObligationCause::dummy(),
1241                |ty| wfcx.deeply_normalize(span, loc, ty),
1242                || {},
1243            );
1244
1245            matches!(tail.kind(), ty::Foreign(_))
1246        };
1247        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1248
1249        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1250        if forbid_unsized {
1251            let span = tcx.def_span(item_id);
1252            wfcx.register_bound(
1253                traits::ObligationCause::new(
1254                    span,
1255                    wfcx.body_def_id,
1256                    ObligationCauseCode::SizedConstOrStatic,
1257                ),
1258                wfcx.param_env,
1259                item_ty,
1260                tcx.require_lang_item(LangItem::Sized, span),
1261            );
1262        }
1263
1264        // Ensure that the end result is `Sync` in a non-thread local `static`.
1265        let should_check_for_sync = should_check_for_sync
1266            && !is_foreign_item
1267            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1268            && !tcx.is_thread_local_static(item_id.to_def_id());
1269
1270        if should_check_for_sync {
1271            wfcx.register_bound(
1272                traits::ObligationCause::new(
1273                    span,
1274                    wfcx.body_def_id,
1275                    ObligationCauseCode::SharedStatic,
1276                ),
1277                wfcx.param_env,
1278                item_ty,
1279                tcx.require_lang_item(LangItem::Sync, span),
1280            );
1281        }
1282        Ok(())
1283    })
1284}
1285
1286#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_type_const",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1286u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "item_ty",
                                                    "has_value"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&has_value as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            let span = tcx.def_span(def_id);
            wfcx.register_bound(ObligationCause::new(span, def_id,
                    ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
                item_ty, tcx.require_lang_item(LangItem::ConstParamTy, span));
            if has_value {
                let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
                let norm_ct =
                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                        raw_ct);
                wfcx.register_wf_obligation(span,
                    Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
                wfcx.register_obligation(Obligation::new(tcx,
                        ObligationCause::new(span, def_id,
                            ObligationCauseCode::WellFormed(None)), wfcx.param_env,
                        ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
                                item_ty))));
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1287pub(super) fn check_type_const<'tcx>(
1288    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1289    def_id: LocalDefId,
1290    item_ty: Ty<'tcx>,
1291    has_value: bool,
1292) -> Result<(), ErrorGuaranteed> {
1293    let tcx = wfcx.tcx();
1294    let span = tcx.def_span(def_id);
1295
1296    wfcx.register_bound(
1297        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1298        wfcx.param_env,
1299        item_ty,
1300        tcx.require_lang_item(LangItem::ConstParamTy, span),
1301    );
1302
1303    if has_value {
1304        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1305        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1306        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1307
1308        wfcx.register_obligation(Obligation::new(
1309            tcx,
1310            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1311            wfcx.param_env,
1312            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1313        ));
1314    }
1315    Ok(())
1316}
1317
1318#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_impl",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1318u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            enter_wf_checking_ctxt(tcx, item.owner_id.def_id,
                |wfcx|
                    {
                        match impl_.of_trait {
                            Some(of_trait) => {
                                let trait_ref =
                                    tcx.impl_trait_ref(item.owner_id).instantiate_identity();
                                tcx.ensure_result().coherent_trait(trait_ref.def_id)?;
                                let trait_span = of_trait.trait_ref.path.span;
                                let trait_ref =
                                    wfcx.deeply_normalize(trait_span,
                                        Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                        trait_ref);
                                let trait_pred =
                                    ty::TraitPredicate {
                                        trait_ref,
                                        polarity: ty::PredicatePolarity::Positive,
                                    };
                                let mut obligations =
                                    traits::wf::trait_obligations(wfcx.infcx, wfcx.param_env,
                                        wfcx.body_def_id, trait_pred, trait_span, item);
                                for obligation in &mut obligations {
                                    if obligation.cause.span != trait_span { continue; }
                                    if let Some(pred) = obligation.predicate.as_trait_clause()
                                            && pred.skip_binder().self_ty() == trait_ref.self_ty() {
                                        obligation.cause.span = impl_.self_ty.span;
                                    }
                                    if let Some(pred) =
                                                obligation.predicate.as_projection_clause() &&
                                            pred.skip_binder().self_ty() == trait_ref.self_ty() {
                                        obligation.cause.span = impl_.self_ty.span;
                                    }
                                }
                                if tcx.is_conditionally_const(item.owner_id.def_id) {
                                    for (bound, _) in
                                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx,
                                            trait_ref.args) {
                                        let bound =
                                            wfcx.normalize(item.span,
                                                Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                                bound);
                                        wfcx.register_obligation(Obligation::new(tcx,
                                                ObligationCause::new(impl_.self_ty.span, wfcx.body_def_id,
                                                    ObligationCauseCode::WellFormed(None)), wfcx.param_env,
                                                bound.to_host_effect_clause(tcx,
                                                    ty::BoundConstness::Maybe)))
                                    }
                                }
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1390",
                                                        "rustc_hir_analysis::check::wfcheck",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1390u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                                        ::tracing_core::field::FieldSet::new(&["obligations"],
                                                            ::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};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&obligations)
                                                                            as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                wfcx.register_obligations(obligations);
                            }
                            None => {
                                let self_ty =
                                    tcx.type_of(item.owner_id).instantiate_identity();
                                let self_ty =
                                    wfcx.deeply_normalize(item.span,
                                        Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                        self_ty);
                                wfcx.register_wf_obligation(impl_.self_ty.span,
                                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                    self_ty.into());
                            }
                        }
                        check_where_clauses(wfcx, item.owner_id.def_id);
                        Ok(())
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx, impl_))]
1319fn check_impl<'tcx>(
1320    tcx: TyCtxt<'tcx>,
1321    item: &'tcx hir::Item<'tcx>,
1322    impl_: &hir::Impl<'_>,
1323) -> Result<(), ErrorGuaranteed> {
1324    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1325        match impl_.of_trait {
1326            Some(of_trait) => {
1327                // `#[rustc_reservation_impl]` impls are not real impls and
1328                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1329                // won't hold).
1330                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1331                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1332                // case other `Foo` impls are incoherent.
1333                tcx.ensure_result().coherent_trait(trait_ref.def_id)?;
1334                let trait_span = of_trait.trait_ref.path.span;
1335                let trait_ref = wfcx.deeply_normalize(
1336                    trait_span,
1337                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1338                    trait_ref,
1339                );
1340                let trait_pred =
1341                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1342                let mut obligations = traits::wf::trait_obligations(
1343                    wfcx.infcx,
1344                    wfcx.param_env,
1345                    wfcx.body_def_id,
1346                    trait_pred,
1347                    trait_span,
1348                    item,
1349                );
1350                for obligation in &mut obligations {
1351                    if obligation.cause.span != trait_span {
1352                        // We already have a better span.
1353                        continue;
1354                    }
1355                    if let Some(pred) = obligation.predicate.as_trait_clause()
1356                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1357                    {
1358                        obligation.cause.span = impl_.self_ty.span;
1359                    }
1360                    if let Some(pred) = obligation.predicate.as_projection_clause()
1361                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1362                    {
1363                        obligation.cause.span = impl_.self_ty.span;
1364                    }
1365                }
1366
1367                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1368                if tcx.is_conditionally_const(item.owner_id.def_id) {
1369                    for (bound, _) in
1370                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1371                    {
1372                        let bound = wfcx.normalize(
1373                            item.span,
1374                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1375                            bound,
1376                        );
1377                        wfcx.register_obligation(Obligation::new(
1378                            tcx,
1379                            ObligationCause::new(
1380                                impl_.self_ty.span,
1381                                wfcx.body_def_id,
1382                                ObligationCauseCode::WellFormed(None),
1383                            ),
1384                            wfcx.param_env,
1385                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1386                        ))
1387                    }
1388                }
1389
1390                debug!(?obligations);
1391                wfcx.register_obligations(obligations);
1392            }
1393            None => {
1394                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1395                let self_ty = wfcx.deeply_normalize(
1396                    item.span,
1397                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1398                    self_ty,
1399                );
1400                wfcx.register_wf_obligation(
1401                    impl_.self_ty.span,
1402                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1403                    self_ty.into(),
1404                );
1405            }
1406        }
1407
1408        check_where_clauses(wfcx, item.owner_id.def_id);
1409        Ok(())
1410    })
1411}
1412
1413/// Checks where-clauses and inline bounds that are declared on `def_id`.
1414#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_where_clauses",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1414u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = wfcx.infcx;
            let tcx = wfcx.tcx();
            let predicates = tcx.predicates_of(def_id.to_def_id());
            let generics = tcx.generics_of(def_id);
            for param in &generics.own_params {
                if let Some(default) =
                        param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
                    {
                    if !default.has_param() {
                        wfcx.register_wf_obligation(tcx.def_span(param.def_id),
                            (#[allow(non_exhaustive_omitted_patterns)] match param.kind
                                    {
                                    GenericParamDefKind::Type { .. } => true,
                                    _ => false,
                                }).then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
                            default.as_term().unwrap());
                    } else {
                        let GenericArgKind::Const(ct) =
                            default.kind() else { continue; };
                        let ct_ty =
                            match ct.kind() {
                                ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
                                    ty::ConstKind::Bound(_, _) =>
                                    ::core::panicking::panic("internal error: entered unreachable code"),
                                ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
                                    continue,
                                ty::ConstKind::Value(cv) => cv.ty,
                                ty::ConstKind::Unevaluated(uv) => {
                                    infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
                                }
                                ty::ConstKind::Param(param_ct) => {
                                    param_ct.find_const_ty_from_env(wfcx.param_env)
                                }
                            };
                        let param_ty =
                            tcx.type_of(param.def_id).instantiate_identity();
                        if !ct_ty.has_param() && !param_ty.has_param() {
                            let cause =
                                traits::ObligationCause::new(tcx.def_span(param.def_id),
                                    wfcx.body_def_id, ObligationCauseCode::WellFormed(None));
                            wfcx.register_obligation(Obligation::new(tcx, cause,
                                    wfcx.param_env,
                                    ty::ClauseKind::ConstArgHasType(ct, param_ty)));
                        }
                    }
                }
            }
            let args =
                GenericArgs::for_item(tcx, def_id.to_def_id(),
                    |param, _|
                        {
                            if param.index >= generics.parent_count as u32 &&
                                        let Some(default) =
                                            param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
                                    && !default.has_param() {
                                return default;
                            }
                            tcx.mk_param_from_def(param)
                        });
            let default_obligations =
                predicates.predicates.iter().flat_map(|&(pred, sp)|
                            {
                                struct CountParams {
                                    params: FxHashSet<u32>,
                                }
                                #[automatically_derived]
                                impl ::core::default::Default for CountParams {
                                    #[inline]
                                    fn default() -> CountParams {
                                        CountParams { params: ::core::default::Default::default() }
                                    }
                                }
                                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
                                    type Result = ControlFlow<()>;
                                    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
                                        if let ty::Param(param) = t.kind() {
                                            self.params.insert(param.index);
                                        }
                                        t.super_visit_with(self)
                                    }
                                    fn visit_region(&mut self, _: ty::Region<'tcx>)
                                        -> Self::Result {
                                        ControlFlow::Break(())
                                    }
                                    fn visit_const(&mut self, c: ty::Const<'tcx>)
                                        -> Self::Result {
                                        if let ty::ConstKind::Param(param) = c.kind() {
                                            self.params.insert(param.index);
                                        }
                                        c.super_visit_with(self)
                                    }
                                }
                                let mut param_count = CountParams::default();
                                let has_region =
                                    pred.visit_with(&mut param_count).is_break();
                                let instantiated_pred =
                                    ty::EarlyBinder::bind(pred).instantiate(tcx, args);
                                if instantiated_pred.has_non_region_param() ||
                                            param_count.params.len() > 1 || has_region {
                                    None
                                } else if predicates.predicates.iter().any(|&(p, _)|
                                            p == instantiated_pred) {
                                    None
                                } else { Some((instantiated_pred, sp)) }
                            }).map(|(pred, sp)|
                        {
                            let pred = wfcx.normalize(sp, None, pred);
                            let cause =
                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                            Obligation::new(tcx, cause, wfcx.param_env, pred)
                        });
            let predicates = predicates.instantiate_identity(tcx);
            let assoc_const_obligations: Vec<_> =
                predicates.predicates.iter().copied().zip(predicates.spans.iter().copied()).filter_map(|(clause,
                                sp)|
                            {
                                let proj = clause.as_projection_clause()?;
                                let pred_binder =
                                    proj.map_bound(|pred|
                                                {
                                                    pred.term.as_const().map(|ct|
                                                            {
                                                                let assoc_const_ty =
                                                                    tcx.type_of(pred.projection_term.def_id).instantiate(tcx,
                                                                        pred.projection_term.args);
                                                                ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
                                                            })
                                                }).transpose();
                                pred_binder.map(|pred_binder|
                                        {
                                            let cause =
                                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                                            Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
                                        })
                            }).collect();
            match (&predicates.predicates.len(), &predicates.spans.len()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let wf_obligations =
                predicates.into_iter().flat_map(|(p, sp)|
                        {
                            traits::wf::clause_obligations(infcx, wfcx.param_env,
                                wfcx.body_def_id, p, sp)
                        });
            let obligations: Vec<_> =
                wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
            wfcx.register_obligations(obligations);
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1415pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1416    let infcx = wfcx.infcx;
1417    let tcx = wfcx.tcx();
1418
1419    let predicates = tcx.predicates_of(def_id.to_def_id());
1420    let generics = tcx.generics_of(def_id);
1421
1422    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1423    // For example, this forbids the declaration:
1424    //
1425    //     struct Foo<T = Vec<[u32]>> { .. }
1426    //
1427    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1428    for param in &generics.own_params {
1429        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1430            // Ignore dependent defaults -- that is, where the default of one type
1431            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1432            // be sure if it will error or not as user might always specify the other.
1433            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1434            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1435            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1436            if !default.has_param() {
1437                wfcx.register_wf_obligation(
1438                    tcx.def_span(param.def_id),
1439                    matches!(param.kind, GenericParamDefKind::Type { .. })
1440                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1441                    default.as_term().unwrap(),
1442                );
1443            } else {
1444                // If we've got a generic const parameter we still want to check its
1445                // type is correct in case both it and the param type are fully concrete.
1446                let GenericArgKind::Const(ct) = default.kind() else {
1447                    continue;
1448                };
1449
1450                let ct_ty = match ct.kind() {
1451                    ty::ConstKind::Infer(_)
1452                    | ty::ConstKind::Placeholder(_)
1453                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1454                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1455                    ty::ConstKind::Value(cv) => cv.ty,
1456                    ty::ConstKind::Unevaluated(uv) => {
1457                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1458                    }
1459                    ty::ConstKind::Param(param_ct) => {
1460                        param_ct.find_const_ty_from_env(wfcx.param_env)
1461                    }
1462                };
1463
1464                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1465                if !ct_ty.has_param() && !param_ty.has_param() {
1466                    let cause = traits::ObligationCause::new(
1467                        tcx.def_span(param.def_id),
1468                        wfcx.body_def_id,
1469                        ObligationCauseCode::WellFormed(None),
1470                    );
1471                    wfcx.register_obligation(Obligation::new(
1472                        tcx,
1473                        cause,
1474                        wfcx.param_env,
1475                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1476                    ));
1477                }
1478            }
1479        }
1480    }
1481
1482    // Check that trait predicates are WF when params are instantiated with their defaults.
1483    // We don't want to overly constrain the predicates that may be written but we want to
1484    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1485    // Therefore we check if a predicate which contains a single type param
1486    // with a concrete default is WF with that default instantiated.
1487    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1488    //
1489    // First we build the defaulted generic parameters.
1490    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1491        if param.index >= generics.parent_count as u32
1492            // If the param has a default, ...
1493            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1494            // ... and it's not a dependent default, ...
1495            && !default.has_param()
1496        {
1497            // ... then instantiate it with the default.
1498            return default;
1499        }
1500        tcx.mk_param_from_def(param)
1501    });
1502
1503    // Now we build the instantiated predicates.
1504    let default_obligations = predicates
1505        .predicates
1506        .iter()
1507        .flat_map(|&(pred, sp)| {
1508            #[derive(Default)]
1509            struct CountParams {
1510                params: FxHashSet<u32>,
1511            }
1512            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1513                type Result = ControlFlow<()>;
1514                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1515                    if let ty::Param(param) = t.kind() {
1516                        self.params.insert(param.index);
1517                    }
1518                    t.super_visit_with(self)
1519                }
1520
1521                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1522                    ControlFlow::Break(())
1523                }
1524
1525                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1526                    if let ty::ConstKind::Param(param) = c.kind() {
1527                        self.params.insert(param.index);
1528                    }
1529                    c.super_visit_with(self)
1530                }
1531            }
1532            let mut param_count = CountParams::default();
1533            let has_region = pred.visit_with(&mut param_count).is_break();
1534            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1535            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1536            // or preds with multiple params.
1537            if instantiated_pred.has_non_region_param()
1538                || param_count.params.len() > 1
1539                || has_region
1540            {
1541                None
1542            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1543                // Avoid duplication of predicates that contain no parameters, for example.
1544                None
1545            } else {
1546                Some((instantiated_pred, sp))
1547            }
1548        })
1549        .map(|(pred, sp)| {
1550            // Convert each of those into an obligation. So if you have
1551            // something like `struct Foo<T: Copy = String>`, we would
1552            // take that predicate `T: Copy`, instantiated with `String: Copy`
1553            // (actually that happens in the previous `flat_map` call),
1554            // and then try to prove it (in this case, we'll fail).
1555            //
1556            // Note the subtle difference from how we handle `predicates`
1557            // below: there, we are not trying to prove those predicates
1558            // to be *true* but merely *well-formed*.
1559            let pred = wfcx.normalize(sp, None, pred);
1560            let cause = traits::ObligationCause::new(
1561                sp,
1562                wfcx.body_def_id,
1563                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1564            );
1565            Obligation::new(tcx, cause, wfcx.param_env, pred)
1566        });
1567
1568    let predicates = predicates.instantiate_identity(tcx);
1569
1570    let assoc_const_obligations: Vec<_> = predicates
1571        .predicates
1572        .iter()
1573        .copied()
1574        .zip(predicates.spans.iter().copied())
1575        .filter_map(|(clause, sp)| {
1576            let proj = clause.as_projection_clause()?;
1577            let pred_binder = proj
1578                .map_bound(|pred| {
1579                    pred.term.as_const().map(|ct| {
1580                        let assoc_const_ty = tcx
1581                            .type_of(pred.projection_term.def_id)
1582                            .instantiate(tcx, pred.projection_term.args);
1583                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1584                    })
1585                })
1586                .transpose();
1587            pred_binder.map(|pred_binder| {
1588                let cause = traits::ObligationCause::new(
1589                    sp,
1590                    wfcx.body_def_id,
1591                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1592                );
1593                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1594            })
1595        })
1596        .collect();
1597
1598    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1599    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1600        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1601    });
1602    let obligations: Vec<_> =
1603        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1604    wfcx.register_obligations(obligations);
1605}
1606
1607#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_fn_or_method",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1607u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["sig", "def_id"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            let mut sig =
                tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
            let arg_span =
                |idx|
                    hir_decl.inputs.get(idx).map_or(hir_decl.output.span(),
                        |arg: &hir::Ty<'_>| arg.span);
            sig.inputs_and_output =
                tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx,
                                ty)|
                            {
                                wfcx.deeply_normalize(arg_span(idx),
                                    Some(WellFormedLoc::Param {
                                            function: def_id,
                                            param_idx: idx,
                                        }), ty)
                            }));
            for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
                wfcx.register_wf_obligation(arg_span(idx),
                    Some(WellFormedLoc::Param {
                            function: def_id,
                            param_idx: idx,
                        }), ty.into());
            }
            check_where_clauses(wfcx, def_id);
            if sig.abi == ExternAbi::RustCall {
                let span = tcx.def_span(def_id);
                let has_implicit_self =
                    hir_decl.implicit_self != hir::ImplicitSelfKind::None;
                let mut inputs =
                    sig.inputs().iter().skip(if has_implicit_self {
                            1
                        } else { 0 });
                if let Some(ty) = inputs.next() {
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(hir::LangItem::Tuple, span));
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(hir::LangItem::Sized, span));
                } else {
                    tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
                            |input| input.span),
                        "functions with the \"rust-call\" ABI must take a single non-self tuple argument");
                }
                if inputs.next().is_some() {
                    tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
                            |input| input.span),
                        "functions with the \"rust-call\" ABI must take a single non-self tuple argument");
                }
            }
            if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
                let span =
                    match hir_decl.output {
                        hir::FnRetTy::Return(ty) => ty.span,
                        hir::FnRetTy::DefaultReturn(_) => body.value.span,
                    };
                wfcx.register_bound(ObligationCause::new(span, def_id,
                        ObligationCauseCode::SizedReturnType), wfcx.param_env,
                    sig.output(), tcx.require_lang_item(LangItem::Sized, span));
            }
        }
    }
}#[instrument(level = "debug", skip(wfcx, hir_decl))]
1608fn check_fn_or_method<'tcx>(
1609    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1610    sig: ty::PolyFnSig<'tcx>,
1611    hir_decl: &hir::FnDecl<'_>,
1612    def_id: LocalDefId,
1613) {
1614    let tcx = wfcx.tcx();
1615    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1616
1617    // Normalize the input and output types one at a time, using a different
1618    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1619    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1620    // for each type, preventing the HIR wf check from generating
1621    // a nice error message.
1622    let arg_span =
1623        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1624
1625    sig.inputs_and_output =
1626        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1627            wfcx.deeply_normalize(
1628                arg_span(idx),
1629                Some(WellFormedLoc::Param {
1630                    function: def_id,
1631                    // Note that the `param_idx` of the output type is
1632                    // one greater than the index of the last input type.
1633                    param_idx: idx,
1634                }),
1635                ty,
1636            )
1637        }));
1638
1639    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1640        wfcx.register_wf_obligation(
1641            arg_span(idx),
1642            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1643            ty.into(),
1644        );
1645    }
1646
1647    check_where_clauses(wfcx, def_id);
1648
1649    if sig.abi == ExternAbi::RustCall {
1650        let span = tcx.def_span(def_id);
1651        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1652        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1653        // Check that the argument is a tuple and is sized
1654        if let Some(ty) = inputs.next() {
1655            wfcx.register_bound(
1656                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1657                wfcx.param_env,
1658                *ty,
1659                tcx.require_lang_item(hir::LangItem::Tuple, span),
1660            );
1661            wfcx.register_bound(
1662                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1663                wfcx.param_env,
1664                *ty,
1665                tcx.require_lang_item(hir::LangItem::Sized, span),
1666            );
1667        } else {
1668            tcx.dcx().span_err(
1669                hir_decl.inputs.last().map_or(span, |input| input.span),
1670                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1671            );
1672        }
1673        // No more inputs other than the `self` type and the tuple type
1674        if inputs.next().is_some() {
1675            tcx.dcx().span_err(
1676                hir_decl.inputs.last().map_or(span, |input| input.span),
1677                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1678            );
1679        }
1680    }
1681
1682    // If the function has a body, additionally require that the return type is sized.
1683    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1684        let span = match hir_decl.output {
1685            hir::FnRetTy::Return(ty) => ty.span,
1686            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1687        };
1688
1689        wfcx.register_bound(
1690            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1691            wfcx.param_env,
1692            sig.output(),
1693            tcx.require_lang_item(LangItem::Sized, span),
1694        );
1695    }
1696}
1697
1698/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1699#[derive(#[automatically_derived]
impl ::core::clone::Clone for ArbitrarySelfTypesLevel {
    #[inline]
    fn clone(&self) -> ArbitrarySelfTypesLevel { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ArbitrarySelfTypesLevel { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for ArbitrarySelfTypesLevel {
    #[inline]
    fn eq(&self, other: &ArbitrarySelfTypesLevel) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
1700enum ArbitrarySelfTypesLevel {
1701    Basic,        // just arbitrary_self_types
1702    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1703}
1704
1705#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_method_receiver",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1705u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["fn_sig", "method",
                                                    "self_ty"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            if !method.is_method() { return Ok(()); }
            let span = fn_sig.decl.inputs[0].span;
            let loc =
                Some(WellFormedLoc::Param {
                        function: method.def_id.expect_local(),
                        param_idx: 0,
                    });
            let sig = tcx.fn_sig(method.def_id).instantiate_identity();
            let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
            let sig = wfcx.normalize(DUMMY_SP, loc, sig);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1725",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1725u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("check_method_receiver: sig={0:?}",
                                                                sig) as &dyn Value))])
                        });
                } else { ; }
            };
            let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
            let receiver_ty = sig.inputs()[0];
            let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
            receiver_ty.error_reported()?;
            let arbitrary_self_types_level =
                if tcx.features().arbitrary_self_types_pointers() {
                    Some(ArbitrarySelfTypesLevel::WithPointers)
                } else if tcx.features().arbitrary_self_types() {
                    Some(ArbitrarySelfTypesLevel::Basic)
                } else { None };
            let generics = tcx.generics_of(method.def_id);
            let receiver_validity =
                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                    arbitrary_self_types_level, generics);
            if let Err(receiver_validity_err) = receiver_validity {
                return Err(match arbitrary_self_types_level {
                            None if
                                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                                        Some(ArbitrarySelfTypesLevel::Basic), generics).is_ok() => {
                                feature_err(&tcx.sess, sym::arbitrary_self_types, span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types` feature",
                                                            receiver_ty))
                                                })).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
                            }
                            None | Some(ArbitrarySelfTypesLevel::Basic) if
                                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                                        Some(ArbitrarySelfTypesLevel::WithPointers),
                                        generics).is_ok() => {
                                feature_err(&tcx.sess, sym::arbitrary_self_types_pointers,
                                            span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types_pointers` feature",
                                                            receiver_ty))
                                                })).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
                            }
                            _ => {
                                match receiver_validity_err {
                                    ReceiverValidityError::DoesNotDeref if
                                        arbitrary_self_types_level.is_some() => {
                                        let hint =
                                            match receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def().and_then(|adt_def|
                                                        tcx.get_diagnostic_name(adt_def.did())) {
                                                Some(sym::RcWeak | sym::ArcWeak) =>
                                                    Some(InvalidReceiverTyHint::Weak),
                                                Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
                                                _ => None,
                                            };
                                        tcx.dcx().emit_err(errors::InvalidReceiverTy {
                                                span,
                                                receiver_ty,
                                                hint,
                                            })
                                    }
                                    ReceiverValidityError::DoesNotDeref => {
                                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
                                                span,
                                                receiver_ty,
                                            })
                                    }
                                    ReceiverValidityError::MethodGenericParamUsed => {
                                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy {
                                                span,
                                                receiver_ty,
                                            })
                                    }
                                }
                            }
                        });
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1706fn check_method_receiver<'tcx>(
1707    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1708    fn_sig: &hir::FnSig<'_>,
1709    method: ty::AssocItem,
1710    self_ty: Ty<'tcx>,
1711) -> Result<(), ErrorGuaranteed> {
1712    let tcx = wfcx.tcx();
1713
1714    if !method.is_method() {
1715        return Ok(());
1716    }
1717
1718    let span = fn_sig.decl.inputs[0].span;
1719    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1720
1721    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1722    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1723    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1724
1725    debug!("check_method_receiver: sig={:?}", sig);
1726
1727    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1728
1729    let receiver_ty = sig.inputs()[0];
1730    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1731
1732    // If the receiver already has errors reported, consider it valid to avoid
1733    // unnecessary errors (#58712).
1734    receiver_ty.error_reported()?;
1735
1736    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1737        Some(ArbitrarySelfTypesLevel::WithPointers)
1738    } else if tcx.features().arbitrary_self_types() {
1739        Some(ArbitrarySelfTypesLevel::Basic)
1740    } else {
1741        None
1742    };
1743    let generics = tcx.generics_of(method.def_id);
1744
1745    let receiver_validity =
1746        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1747    if let Err(receiver_validity_err) = receiver_validity {
1748        return Err(match arbitrary_self_types_level {
1749            // Wherever possible, emit a message advising folks that the features
1750            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1751            // have helped.
1752            None if receiver_is_valid(
1753                wfcx,
1754                span,
1755                receiver_ty,
1756                self_ty,
1757                Some(ArbitrarySelfTypesLevel::Basic),
1758                generics,
1759            )
1760            .is_ok() =>
1761            {
1762                // Report error; would have worked with `arbitrary_self_types`.
1763                feature_err(
1764                    &tcx.sess,
1765                    sym::arbitrary_self_types,
1766                    span,
1767                    format!(
1768                        "`{receiver_ty}` cannot be used as the type of `self` without \
1769                            the `arbitrary_self_types` feature",
1770                    ),
1771                )
1772                .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1773                .emit()
1774            }
1775            None | Some(ArbitrarySelfTypesLevel::Basic)
1776                if receiver_is_valid(
1777                    wfcx,
1778                    span,
1779                    receiver_ty,
1780                    self_ty,
1781                    Some(ArbitrarySelfTypesLevel::WithPointers),
1782                    generics,
1783                )
1784                .is_ok() =>
1785            {
1786                // Report error; would have worked with `arbitrary_self_types_pointers`.
1787                feature_err(
1788                    &tcx.sess,
1789                    sym::arbitrary_self_types_pointers,
1790                    span,
1791                    format!(
1792                        "`{receiver_ty}` cannot be used as the type of `self` without \
1793                            the `arbitrary_self_types_pointers` feature",
1794                    ),
1795                )
1796                .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1797                .emit()
1798            }
1799            _ =>
1800            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1801            {
1802                match receiver_validity_err {
1803                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1804                        let hint = match receiver_ty
1805                            .builtin_deref(false)
1806                            .unwrap_or(receiver_ty)
1807                            .ty_adt_def()
1808                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1809                        {
1810                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1811                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1812                            _ => None,
1813                        };
1814
1815                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1816                    }
1817                    ReceiverValidityError::DoesNotDeref => {
1818                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1819                            span,
1820                            receiver_ty,
1821                        })
1822                    }
1823                    ReceiverValidityError::MethodGenericParamUsed => {
1824                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1825                    }
1826                }
1827            }
1828        });
1829    }
1830    Ok(())
1831}
1832
1833/// Error cases which may be returned from `receiver_is_valid`. These error
1834/// cases are generated in this function as they may be unearthed as we explore
1835/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1836enum ReceiverValidityError {
1837    /// The self type does not get to the receiver type by following the
1838    /// autoderef chain.
1839    DoesNotDeref,
1840    /// A type was found which is a method type parameter, and that's not allowed.
1841    MethodGenericParamUsed,
1842}
1843
1844/// Confirms that a type is not a type parameter referring to one of the
1845/// method's type params.
1846fn confirm_type_is_not_a_method_generic_param(
1847    ty: Ty<'_>,
1848    method_generics: &ty::Generics,
1849) -> Result<(), ReceiverValidityError> {
1850    if let ty::Param(param) = ty.kind() {
1851        if (param.index as usize) >= method_generics.parent_count {
1852            return Err(ReceiverValidityError::MethodGenericParamUsed);
1853        }
1854    }
1855    Ok(())
1856}
1857
1858/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1859/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1860/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1861/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1862/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1863///
1864/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1865/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1866/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1867fn receiver_is_valid<'tcx>(
1868    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1869    span: Span,
1870    receiver_ty: Ty<'tcx>,
1871    self_ty: Ty<'tcx>,
1872    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1873    method_generics: &ty::Generics,
1874) -> Result<(), ReceiverValidityError> {
1875    let infcx = wfcx.infcx;
1876    let tcx = wfcx.tcx();
1877    let cause =
1878        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1879
1880    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1881    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1882        let ocx = ObligationCtxt::new(wfcx.infcx);
1883        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1884        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1885            Ok(())
1886        } else {
1887            Err(NoSolution)
1888        }
1889    }) {
1890        return Ok(());
1891    }
1892
1893    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1894
1895    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1896
1897    // The `arbitrary_self_types` feature allows custom smart pointer
1898    // types to be method receivers, as identified by following the Receiver<Target=T>
1899    // chain.
1900    if arbitrary_self_types_enabled.is_some() {
1901        autoderef = autoderef.use_receiver_trait();
1902    }
1903
1904    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1905    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1906        autoderef = autoderef.include_raw_pointers();
1907    }
1908
1909    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1910    while let Some((potential_self_ty, _)) = autoderef.next() {
1911        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1911",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1911u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
                                                    potential_self_ty, self_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
1912            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1913            potential_self_ty, self_ty
1914        );
1915
1916        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1917
1918        // Check if the self type unifies. If it does, then commit the result
1919        // since it may have region side-effects.
1920        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1921            let ocx = ObligationCtxt::new(wfcx.infcx);
1922            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1923            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1924                Ok(())
1925            } else {
1926                Err(NoSolution)
1927            }
1928        }) {
1929            wfcx.register_obligations(autoderef.into_obligations());
1930            return Ok(());
1931        }
1932
1933        // Without `feature(arbitrary_self_types)`, we require that each step in the
1934        // deref chain implement `LegacyReceiver`.
1935        if arbitrary_self_types_enabled.is_none() {
1936            let legacy_receiver_trait_def_id =
1937                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1938            if !legacy_receiver_is_implemented(
1939                wfcx,
1940                legacy_receiver_trait_def_id,
1941                cause.clone(),
1942                potential_self_ty,
1943            ) {
1944                // We cannot proceed.
1945                break;
1946            }
1947
1948            // Register the bound, in case it has any region side-effects.
1949            wfcx.register_bound(
1950                cause.clone(),
1951                wfcx.param_env,
1952                potential_self_ty,
1953                legacy_receiver_trait_def_id,
1954            );
1955        }
1956    }
1957
1958    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1958",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1958u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
                                                    receiver_ty, self_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1959    Err(ReceiverValidityError::DoesNotDeref)
1960}
1961
1962fn legacy_receiver_is_implemented<'tcx>(
1963    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1964    legacy_receiver_trait_def_id: DefId,
1965    cause: ObligationCause<'tcx>,
1966    receiver_ty: Ty<'tcx>,
1967) -> bool {
1968    let tcx = wfcx.tcx();
1969    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1970
1971    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1972
1973    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1974        true
1975    } else {
1976        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1976",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1976u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
                                                    receiver_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
1977            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1978            receiver_ty
1979        );
1980        false
1981    }
1982}
1983
1984pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1985    match tcx.def_kind(def_id) {
1986        DefKind::Enum | DefKind::Struct | DefKind::Union => {
1987            // Ok
1988        }
1989        DefKind::TyAlias => {
1990            if !tcx.type_alias_is_lazy(def_id) {
    {
        ::core::panicking::panic_fmt(format_args!("should not be computing variance of non-free type alias"));
    }
};assert!(
1991                tcx.type_alias_is_lazy(def_id),
1992                "should not be computing variance of non-free type alias"
1993            );
1994        }
1995        kind => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
    format_args!("cannot compute the variances of {0:?}", kind))span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1996    }
1997
1998    let ty_predicates = tcx.predicates_of(def_id);
1999    match (&ty_predicates.parent, &None) {
    (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!(ty_predicates.parent, None);
2000    let variances = tcx.variances_of(def_id);
2001
2002    let mut constrained_parameters: FxHashSet<_> = variances
2003        .iter()
2004        .enumerate()
2005        .filter(|&(_, &variance)| variance != ty::Bivariant)
2006        .map(|(index, _)| Parameter(index as u32))
2007        .collect();
2008
2009    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2010
2011    // Lazily calculated because it is only needed in case of an error.
2012    let explicitly_bounded_params = LazyCell::new(|| {
2013        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2014        tcx.hir_node_by_def_id(def_id)
2015            .generics()
2016            .unwrap()
2017            .predicates
2018            .iter()
2019            .filter_map(|predicate| match predicate.kind {
2020                hir::WherePredicateKind::BoundPredicate(predicate) => {
2021                    match icx.lower_ty(predicate.bounded_ty).kind() {
2022                        ty::Param(data) => Some(Parameter(data.index)),
2023                        _ => None,
2024                    }
2025                }
2026                _ => None,
2027            })
2028            .collect::<FxHashSet<_>>()
2029    });
2030
2031    for (index, _) in variances.iter().enumerate() {
2032        let parameter = Parameter(index as u32);
2033
2034        if constrained_parameters.contains(&parameter) {
2035            continue;
2036        }
2037
2038        let node = tcx.hir_node_by_def_id(def_id);
2039        let item = node.expect_item();
2040        let hir_generics = node.generics().unwrap();
2041        let hir_param = &hir_generics.params[index];
2042
2043        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2044
2045        if ty_param.def_id != hir_param.def_id.into() {
2046            // Valid programs always have lifetimes before types in the generic parameter list.
2047            // ty_generics are normalized to be in this required order, and variances are built
2048            // from ty generics, not from hir generics. but we need hir generics to get
2049            // a span out.
2050            //
2051            // If they aren't in the same order, then the user has written invalid code, and already
2052            // got an error about it (or I'm wrong about this).
2053            tcx.dcx().span_delayed_bug(
2054                hir_param.span,
2055                "hir generics and ty generics in different order",
2056            );
2057            continue;
2058        }
2059
2060        // Look for `ErrorGuaranteed` deeply within this type.
2061        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2062            .type_of(def_id)
2063            .instantiate_identity()
2064            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2065        {
2066            continue;
2067        }
2068
2069        match hir_param.name {
2070            hir::ParamName::Error(_) => {
2071                // Don't report a bivariance error for a lifetime that isn't
2072                // even valid to name.
2073            }
2074            _ => {
2075                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2076                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2077            }
2078        }
2079    }
2080}
2081
2082/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2083struct HasErrorDeep<'tcx> {
2084    tcx: TyCtxt<'tcx>,
2085    seen: FxHashSet<DefId>,
2086}
2087impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2088    type Result = ControlFlow<ErrorGuaranteed>;
2089
2090    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2091        match *ty.kind() {
2092            ty::Adt(def, _) => {
2093                if self.seen.insert(def.did()) {
2094                    for field in def.all_fields() {
2095                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2096                    }
2097                }
2098            }
2099            ty::Error(guar) => return ControlFlow::Break(guar),
2100            _ => {}
2101        }
2102        ty.super_visit_with(self)
2103    }
2104
2105    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2106        if let Err(guar) = r.error_reported() {
2107            ControlFlow::Break(guar)
2108        } else {
2109            ControlFlow::Continue(())
2110        }
2111    }
2112
2113    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2114        if let Err(guar) = c.error_reported() {
2115            ControlFlow::Break(guar)
2116        } else {
2117            ControlFlow::Continue(())
2118        }
2119    }
2120}
2121
2122fn report_bivariance<'tcx>(
2123    tcx: TyCtxt<'tcx>,
2124    param: &'tcx hir::GenericParam<'tcx>,
2125    has_explicit_bounds: bool,
2126    item: &'tcx hir::Item<'tcx>,
2127) -> ErrorGuaranteed {
2128    let param_name = param.name.ident();
2129
2130    let help = match item.kind {
2131        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2132            if let Some(def_id) = tcx.lang_items().phantom_data() {
2133                errors::UnusedGenericParameterHelp::Adt {
2134                    param_name,
2135                    phantom_data: tcx.def_path_str(def_id),
2136                }
2137            } else {
2138                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2139            }
2140        }
2141        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2142        item_kind => ::rustc_middle::util::bug::bug_fmt(format_args!("report_bivariance: unexpected item kind: {0:?}",
        item_kind))bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2143    };
2144
2145    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2146    intravisit::walk_item(
2147        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2148        item,
2149    );
2150
2151    if !usage_spans.is_empty() {
2152        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2153        // not actually looking into substitutions, just walking through fields / the "RHS".
2154        // We don't recurse into the hidden types of opaques or anything else fancy.
2155        let item_def_id = item.owner_id.to_def_id();
2156        let is_probably_cyclical =
2157            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2158                .visit_def(item_def_id)
2159                .is_break();
2160        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2161        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2162        // alias, and we should call those parameter usages recursive rather than just saying
2163        // they're unused...
2164        //
2165        // We currently report *all* of the parameter usages, since computing the exact
2166        // subset is very involved, and the fact we're mentioning recursion at all is
2167        // likely to guide the user in the right direction.
2168        if is_probably_cyclical {
2169            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2170                spans: usage_spans,
2171                param_span: param.span,
2172                param_name,
2173                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2174                help,
2175                note: (),
2176            });
2177        }
2178    }
2179
2180    let const_param_help =
2181        #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    hir::GenericParamKind::Type { .. } if !has_explicit_bounds => true,
    _ => false,
}matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2182
2183    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2184        span: param.span,
2185        param_name,
2186        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2187        usage_spans,
2188        help,
2189        const_param_help,
2190    });
2191    diag.code(E0392);
2192    if item.kind.recovered() {
2193        // Silence potentially redundant error, as the item had a parse error.
2194        diag.delay_as_bug()
2195    } else {
2196        diag.emit()
2197    }
2198}
2199
2200/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2201/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2202/// cyclical.
2203///
2204/// Notably, we don't consider substitutions here, so this may have false positives.
2205struct IsProbablyCyclical<'tcx> {
2206    tcx: TyCtxt<'tcx>,
2207    item_def_id: DefId,
2208    seen: FxHashSet<DefId>,
2209}
2210
2211impl<'tcx> IsProbablyCyclical<'tcx> {
2212    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2213        match self.tcx.def_kind(def_id) {
2214            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2215                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2216                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2217                })
2218            }
2219            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2220                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2221            }
2222            _ => ControlFlow::Continue(()),
2223        }
2224    }
2225}
2226
2227impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2228    type Result = ControlFlow<(), ()>;
2229
2230    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2231        let def_id = match ty.kind() {
2232            ty::Adt(adt_def, _) => Some(adt_def.did()),
2233            ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2234            _ => None,
2235        };
2236        if let Some(def_id) = def_id {
2237            if def_id == self.item_def_id {
2238                return ControlFlow::Break(());
2239            }
2240            if self.seen.insert(def_id) {
2241                self.visit_def(def_id)?;
2242            }
2243        }
2244        ty.super_visit_with(self)
2245    }
2246}
2247
2248/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2249///
2250/// This is used to report places where the user has used parameters in a
2251/// non-variance-constraining way for better bivariance errors.
2252struct CollectUsageSpans<'a> {
2253    spans: &'a mut Vec<Span>,
2254    param_def_id: DefId,
2255}
2256
2257impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2258    type Result = ();
2259
2260    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2261        // Skip the generics. We only care about fields, not where clause/param bounds.
2262    }
2263
2264    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2265        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2266            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2267                && def_id == self.param_def_id
2268            {
2269                self.spans.push(t.span);
2270                return;
2271            } else if let Res::SelfTyAlias { .. } = qpath.res {
2272                self.spans.push(t.span);
2273                return;
2274            }
2275        }
2276        intravisit::walk_ty(self, t);
2277    }
2278}
2279
2280impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2281    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2282    /// aren't true.
2283    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_false_global_bounds",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2283u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.ocx.infcx.tcx;
            let mut span = tcx.def_span(self.body_def_id);
            let empty_env = ty::ParamEnv::empty();
            let predicates_with_span =
                tcx.predicates_of(self.body_def_id).predicates.iter().copied();
            let implied_obligations =
                traits::elaborate(tcx, predicates_with_span);
            for (pred, obligation_span) in implied_obligations {
                match pred.kind().skip_binder() {
                    ty::ClauseKind::WellFormed(..) |
                        ty::ClauseKind::UnstableFeature(..) => continue,
                    _ => {}
                }
                if pred.is_global() &&
                        !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
                    let pred = self.normalize(span, None, pred);
                    let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
                    if let Some(hir::Generics { predicates, .. }) =
                            hir_node.generics() {
                        span =
                            predicates.iter().find(|pred|
                                            pred.span.contains(obligation_span)).map(|pred|
                                        pred.span).unwrap_or(obligation_span);
                    }
                    let obligation =
                        Obligation::new(tcx,
                            traits::ObligationCause::new(span, self.body_def_id,
                                ObligationCauseCode::TrivialBound), empty_env, pred);
                    self.ocx.register_obligation(obligation);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2284    fn check_false_global_bounds(&mut self) {
2285        let tcx = self.ocx.infcx.tcx;
2286        let mut span = tcx.def_span(self.body_def_id);
2287        let empty_env = ty::ParamEnv::empty();
2288
2289        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2290        // Check elaborated bounds.
2291        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2292
2293        for (pred, obligation_span) in implied_obligations {
2294            match pred.kind().skip_binder() {
2295                // We lower empty bounds like `Vec<dyn Copy>:` as
2296                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2297                // regular WF checking
2298                ty::ClauseKind::WellFormed(..)
2299                // Unstable feature goals cannot be proven in an empty environment so skip them
2300                | ty::ClauseKind::UnstableFeature(..) => continue,
2301                _ => {}
2302            }
2303
2304            // Match the existing behavior.
2305            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2306                let pred = self.normalize(span, None, pred);
2307
2308                // only use the span of the predicate clause (#90869)
2309                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2310                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2311                    span = predicates
2312                        .iter()
2313                        // There seems to be no better way to find out which predicate we are in
2314                        .find(|pred| pred.span.contains(obligation_span))
2315                        .map(|pred| pred.span)
2316                        .unwrap_or(obligation_span);
2317                }
2318
2319                let obligation = Obligation::new(
2320                    tcx,
2321                    traits::ObligationCause::new(
2322                        span,
2323                        self.body_def_id,
2324                        ObligationCauseCode::TrivialBound,
2325                    ),
2326                    empty_env,
2327                    pred,
2328                );
2329                self.ocx.register_obligation(obligation);
2330            }
2331        }
2332    }
2333}
2334
2335pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2336    let items = tcx.hir_crate_items(());
2337    let res =
2338        items
2339            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2340            .and(
2341                items.par_impl_items(|item| {
2342                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2343                }),
2344            )
2345            .and(items.par_trait_items(|item| {
2346                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2347            }))
2348            .and(items.par_foreign_items(|item| {
2349                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2350            }))
2351            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2352            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2353    super::entry::check_for_entry_fn(tcx);
2354
2355    res
2356}
2357
2358fn lint_redundant_lifetimes<'tcx>(
2359    tcx: TyCtxt<'tcx>,
2360    owner_id: LocalDefId,
2361    outlives_env: &OutlivesEnvironment<'tcx>,
2362) {
2363    let def_kind = tcx.def_kind(owner_id);
2364    match def_kind {
2365        DefKind::Struct
2366        | DefKind::Union
2367        | DefKind::Enum
2368        | DefKind::Trait
2369        | DefKind::TraitAlias
2370        | DefKind::Fn
2371        | DefKind::Const { .. }
2372        | DefKind::Impl { of_trait: _ } => {
2373            // Proceed
2374        }
2375        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2376            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2377                // Don't check for redundant lifetimes for associated items of trait
2378                // implementations, since the signature is required to be compatible
2379                // with the trait, even if the implementation implies some lifetimes
2380                // are redundant.
2381                return;
2382            }
2383        }
2384        DefKind::Mod
2385        | DefKind::Variant
2386        | DefKind::TyAlias
2387        | DefKind::ForeignTy
2388        | DefKind::TyParam
2389        | DefKind::ConstParam
2390        | DefKind::Static { .. }
2391        | DefKind::Ctor(_, _)
2392        | DefKind::Macro(_)
2393        | DefKind::ExternCrate
2394        | DefKind::Use
2395        | DefKind::ForeignMod
2396        | DefKind::AnonConst
2397        | DefKind::InlineConst
2398        | DefKind::OpaqueTy
2399        | DefKind::Field
2400        | DefKind::LifetimeParam
2401        | DefKind::GlobalAsm
2402        | DefKind::Closure
2403        | DefKind::SyntheticCoroutineBody => return,
2404    }
2405
2406    // The ordering of this lifetime map is a bit subtle.
2407    //
2408    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2409    // where we can prove that `'candidate = 'victim`.
2410    //
2411    // `'static` must come first in this list because we can never replace `'static` with
2412    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2413    // suggest replacing `'a` with `'static`.
2414    let mut lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.lifetimes.re_static]))vec![tcx.lifetimes.re_static];
2415    lifetimes.extend(
2416        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2417    );
2418    // If we are in a function, add its late-bound lifetimes too.
2419    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2420        for (idx, var) in
2421            tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2422        {
2423            let ty::BoundVariableKind::Region(kind) = var else { continue };
2424            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2425            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2426        }
2427    }
2428    lifetimes.retain(|candidate| candidate.is_named(tcx));
2429
2430    // Keep track of lifetimes which have already been replaced with other lifetimes.
2431    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2432    // both `'a` and `'b`.
2433    let mut shadowed = FxHashSet::default();
2434
2435    for (idx, &candidate) in lifetimes.iter().enumerate() {
2436        // Don't suggest removing a lifetime twice. We only need to check this
2437        // here and not up in the `victim` loop because equality is transitive,
2438        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2439        // A's victim loop.
2440        if shadowed.contains(&candidate) {
2441            continue;
2442        }
2443
2444        for &victim in &lifetimes[(idx + 1)..] {
2445            // All region parameters should have a `DefId` available as:
2446            // - Late-bound parameters should be of the`BrNamed` variety,
2447            // since we get these signatures straight from `hir_lowering`.
2448            // - Early-bound parameters unconditionally have a `DefId` available.
2449            //
2450            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2451            // can't really suggest to remove them.
2452            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2453                continue;
2454            };
2455
2456            // Do not rename lifetimes not local to this item since they'll overlap
2457            // with the lint running on the parent. We still want to consider parent
2458            // lifetimes which make child lifetimes redundant, otherwise we would
2459            // have truncated the `identity_for_item` args above.
2460            if tcx.parent(def_id) != owner_id.to_def_id() {
2461                continue;
2462            }
2463
2464            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2465            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2466                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2467            {
2468                shadowed.insert(victim);
2469                tcx.emit_node_span_lint(
2470                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2471                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2472                    tcx.def_span(def_id),
2473                    RedundantLifetimeArgsLint { candidate, victim },
2474                );
2475            }
2476        }
2477    }
2478}
2479
2480#[derive(const _: () =
    {
        impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
            RedundantLifetimeArgsLint<'tcx> where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    RedundantLifetimeArgsLint {
                        victim: __binding_0, candidate: __binding_1 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unnecessary lifetime parameter `{$victim}`")));
                        diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")));
                        ;
                        diag.arg("victim", __binding_0);
                        diag.arg("candidate", __binding_1);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
2481#[diag("unnecessary lifetime parameter `{$victim}`")]
2482#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2483struct RedundantLifetimeArgsLint<'tcx> {
2484    /// The lifetime we have found to be redundant.
2485    victim: ty::Region<'tcx>,
2486    // The lifetime we can replace the victim with.
2487    candidate: ty::Region<'tcx>,
2488}