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_infer::traits::PredicateObligations;
19use rustc_lint_defs::builtin::SHADOWING_SUPERTRAIT_ITEMS;
20use rustc_macros::Diagnostic;
21use rustc_middle::mir::interpret::ErrorHandled;
22use rustc_middle::traits::solve::NoSolution;
23use rustc_middle::ty::trait_def::TraitSpecializationKind;
24use rustc_middle::ty::{
25    self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
26    TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
27    Upcast,
28};
29use rustc_middle::{bug, span_bug};
30use rustc_session::parse::feature_err;
31use rustc_span::{DUMMY_SP, Span, sym};
32use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
33use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
34use rustc_trait_selection::traits::misc::{
35    ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
36};
37use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
38use rustc_trait_selection::traits::{
39    self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
40    WellFormedLoc,
41};
42use tracing::{debug, instrument};
43
44use super::compare_eii::compare_eii_function_types;
45use crate::autoderef::Autoderef;
46use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
47use crate::errors;
48use crate::errors::InvalidReceiverTyHint;
49
50pub(super) struct WfCheckingCtxt<'a, 'tcx> {
51    pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
52    body_def_id: LocalDefId,
53    param_env: ty::ParamEnv<'tcx>,
54}
55impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
56    type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
57    fn deref(&self) -> &Self::Target {
58        &self.ocx
59    }
60}
61
62impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
63    fn tcx(&self) -> TyCtxt<'tcx> {
64        self.ocx.infcx.tcx
65    }
66
67    // Convenience function to normalize during wfcheck. This performs
68    // `ObligationCtxt::normalize`, but provides a nice `ObligationCauseCode`.
69    fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
70    where
71        T: TypeFoldable<TyCtxt<'tcx>>,
72    {
73        self.ocx.normalize(
74            &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
75            self.param_env,
76            value,
77        )
78    }
79
80    /// Convenience function to *deeply* normalize during wfcheck. In the old solver,
81    /// this just dispatches to [`WfCheckingCtxt::normalize`], but in the new solver
82    /// this calls `deeply_normalize` and reports errors if they are encountered.
83    ///
84    /// This function should be called in favor of `normalize` in cases where we will
85    /// then check the well-formedness of the type, since we only use the normalized
86    /// signature types for implied bounds when checking regions.
87    // FIXME(-Znext-solver): This should be removed when we compute implied outlives
88    // bounds using the unnormalized signature of the function we're checking.
89    pub(super) fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
90    where
91        T: TypeFoldable<TyCtxt<'tcx>>,
92    {
93        if self.infcx.next_trait_solver() {
94            match self.ocx.deeply_normalize(
95                &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
96                self.param_env,
97                value.clone(),
98            ) {
99                Ok(value) => value,
100                Err(errors) => {
101                    self.infcx.err_ctxt().report_fulfillment_errors(errors);
102                    value
103                }
104            }
105        } else {
106            self.normalize(span, loc, value)
107        }
108    }
109
110    pub(super) fn register_wf_obligation(
111        &self,
112        span: Span,
113        loc: Option<WellFormedLoc>,
114        term: ty::Term<'tcx>,
115    ) {
116        let cause = traits::ObligationCause::new(
117            span,
118            self.body_def_id,
119            ObligationCauseCode::WellFormed(loc),
120        );
121        self.ocx.register_obligation(Obligation::new(
122            self.tcx(),
123            cause,
124            self.param_env,
125            ty::ClauseKind::WellFormed(term),
126        ));
127    }
128
129    pub(super) fn unnormalized_obligations(
130        &self,
131        span: Span,
132        ty: Ty<'tcx>,
133    ) -> Option<PredicateObligations<'tcx>> {
134        traits::wf::unnormalized_obligations(
135            self.ocx.infcx,
136            self.param_env,
137            ty.into(),
138            span,
139            self.body_def_id,
140        )
141    }
142}
143
144pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
145    tcx: TyCtxt<'tcx>,
146    body_def_id: LocalDefId,
147    f: F,
148) -> Result<(), ErrorGuaranteed>
149where
150    F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
151{
152    let param_env = tcx.param_env(body_def_id);
153    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
154    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
155
156    let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
157
158    // As of now, bounds are only checked on lazy type aliases, they're ignored for most type
159    // aliases. So, only check for false global bounds if we're not ignoring bounds altogether.
160    let ignore_bounds =
161        tcx.def_kind(body_def_id) == DefKind::TyAlias && !tcx.type_alias_is_lazy(body_def_id);
162
163    if !ignore_bounds && !tcx.features().trivial_bounds() {
164        wfcx.check_false_global_bounds()
165    }
166    f(&mut wfcx)?;
167
168    let errors = wfcx.evaluate_obligations_error_on_ambiguity();
169    if !errors.is_empty() {
170        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
171    }
172
173    let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
174    {
    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:174",
                        "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(174u32),
                        ::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);
175
176    let infcx_compat = infcx.fork();
177
178    // We specifically want to *disable* the implied bounds hack, first,
179    // so we can detect when failures are due to bevy's implied bounds.
180    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
181        &infcx,
182        body_def_id,
183        param_env,
184        assumed_wf_types.iter().copied(),
185        true,
186    );
187
188    lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
189
190    let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
191    if errors.is_empty() {
192        return Ok(());
193    }
194
195    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
196        &infcx_compat,
197        body_def_id,
198        param_env,
199        assumed_wf_types,
200        // Don't *disable* the implied bounds hack; though this will only apply
201        // the implied bounds hack if this contains `bevy_ecs`'s `ParamSet` type.
202        false,
203    );
204    let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
205    if errors_compat.is_empty() {
206        // FIXME: Once we fix bevy, this would be the place to insert a warning
207        // to upgrade bevy.
208        Ok(())
209    } else {
210        Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
211    }
212}
213
214pub(super) fn check_well_formed(
215    tcx: TyCtxt<'_>,
216    def_id: LocalDefId,
217) -> Result<(), ErrorGuaranteed> {
218    let mut res = crate::check::check::check_item_type(tcx, def_id);
219
220    for param in &tcx.generics_of(def_id).own_params {
221        res = res.and(check_param_wf(tcx, param));
222    }
223
224    res
225}
226
227/// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
228/// well-formed, meaning that they do not require any constraints not declared in the struct
229/// definition itself. For example, this definition would be illegal:
230///
231/// ```rust
232/// struct StaticRef<T> { x: &'static T }
233/// ```
234///
235/// because the type did not declare that `T: 'static`.
236///
237/// We do this check as a pre-pass before checking fn bodies because if these constraints are
238/// not included it frequently leads to confusing errors in fn bodies. So it's better to check
239/// the types first.
240#[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(240u32),
                                    ::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:247",
                                    "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(247u32),
                                    ::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")]
241pub(super) fn check_item<'tcx>(
242    tcx: TyCtxt<'tcx>,
243    item: &'tcx hir::Item<'tcx>,
244) -> Result<(), ErrorGuaranteed> {
245    let def_id = item.owner_id.def_id;
246
247    debug!(
248        ?item.owner_id,
249        item.name = ? tcx.def_path_str(def_id)
250    );
251
252    match item.kind {
253        // Right now we check that every default trait implementation
254        // has an implementation of itself. Basically, a case like:
255        //
256        //     impl Trait for T {}
257        //
258        // has a requirement of `T: Trait` which was required for default
259        // method implementations. Although this could be improved now that
260        // there's a better infrastructure in place for this, it's being left
261        // for a follow-up work.
262        //
263        // Since there's such a requirement, we need to check *just* positive
264        // implementations, otherwise things like:
265        //
266        //     impl !Send for T {}
267        //
268        // won't be allowed unless there's an *explicit* implementation of `Send`
269        // for `T`
270        hir::ItemKind::Impl(ref impl_) => {
271            crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
272            let mut res = Ok(());
273            if let Some(of_trait) = impl_.of_trait {
274                let header = tcx.impl_trait_header(def_id);
275                let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
276                if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
277                    let sp = of_trait.trait_ref.path.span;
278                    res = Err(tcx
279                        .dcx()
280                        .struct_span_err(sp, "impls of auto traits cannot be default")
281                        .with_span_labels(of_trait.defaultness_span, "default because of this")
282                        .with_span_label(sp, "auto trait")
283                        .emit());
284                }
285                match header.polarity {
286                    ty::ImplPolarity::Positive => {
287                        res = res.and(check_impl(tcx, item, impl_));
288                    }
289                    ty::ImplPolarity::Negative => {
290                        let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
291                            bug!("impl_polarity query disagrees with impl's polarity in HIR");
292                        };
293                        // FIXME(#27579): what amount of WF checking do we need for neg impls?
294                        if let hir::Defaultness::Default { .. } = of_trait.defaultness {
295                            let mut spans = vec![span];
296                            spans.extend(of_trait.defaultness_span);
297                            res = Err(struct_span_code_err!(
298                                tcx.dcx(),
299                                spans,
300                                E0750,
301                                "negative impls cannot be default impls"
302                            )
303                            .emit());
304                        }
305                    }
306                    ty::ImplPolarity::Reservation => {
307                        // FIXME: what amount of WF checking do we need for reservation impls?
308                    }
309                }
310            } else {
311                res = res.and(check_impl(tcx, item, impl_));
312            }
313            res
314        }
315        hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
316        hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
317        hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
318        hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
319        hir::ItemKind::Trait(..) => check_trait(tcx, item),
320        hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
321        _ => Ok(()),
322    }
323}
324
325pub(super) fn check_foreign_item<'tcx>(
326    tcx: TyCtxt<'tcx>,
327    item: &'tcx hir::ForeignItem<'tcx>,
328) -> Result<(), ErrorGuaranteed> {
329    let def_id = item.owner_id.def_id;
330
331    {
    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:331",
                        "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(331u32),
                        ::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!(
332        ?item.owner_id,
333        item.name = ? tcx.def_path_str(def_id)
334    );
335
336    match item.kind {
337        hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
338        hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
339    }
340}
341
342pub(crate) fn check_trait_item<'tcx>(
343    tcx: TyCtxt<'tcx>,
344    def_id: LocalDefId,
345) -> Result<(), ErrorGuaranteed> {
346    // Check that an item definition in a subtrait is shadowing a supertrait item.
347    lint_item_shadowing_supertrait_item(tcx, def_id);
348
349    let mut res = Ok(());
350
351    if tcx.def_kind(def_id) == DefKind::AssocFn {
352        for &assoc_ty_def_id in
353            tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
354        {
355            res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
356        }
357    }
358    res
359}
360
361/// Require that the user writes where clauses on GATs for the implicit
362/// outlives bounds involving trait parameters in trait functions and
363/// lifetimes passed as GAT args. See `self-outlives-lint` test.
364///
365/// We use the following trait as an example throughout this function:
366/// ```rust,ignore (this code fails due to this lint)
367/// trait IntoIter {
368///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
369///     type Item<'a>;
370///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
371/// }
372/// ```
373fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
374    // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
375    let mut required_bounds_by_item = FxIndexMap::default();
376    let associated_items = tcx.associated_items(trait_def_id);
377
378    // Loop over all GATs together, because if this lint suggests adding a where-clause bound
379    // to one GAT, it might then require us to an additional bound on another GAT.
380    // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
381    // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
382    // those GATs.
383    loop {
384        let mut should_continue = false;
385        for gat_item in associated_items.in_definition_order() {
386            let gat_def_id = gat_item.def_id.expect_local();
387            let gat_item = tcx.associated_item(gat_def_id);
388            // If this item is not an assoc ty, or has no args, then it's not a GAT
389            if !gat_item.is_type() {
390                continue;
391            }
392            let gat_generics = tcx.generics_of(gat_def_id);
393            // FIXME(jackh726): we can also warn in the more general case
394            if gat_generics.is_own_empty() {
395                continue;
396            }
397
398            // Gather the bounds with which all other items inside of this trait constrain the GAT.
399            // This is calculated by taking the intersection of the bounds that each item
400            // constrains the GAT with individually.
401            let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
402            for item in associated_items.in_definition_order() {
403                let item_def_id = item.def_id.expect_local();
404                // Skip our own GAT, since it does not constrain itself at all.
405                if item_def_id == gat_def_id {
406                    continue;
407                }
408
409                let param_env = tcx.param_env(item_def_id);
410
411                let item_required_bounds = match tcx.associated_item(item_def_id).kind {
412                    // In our example, this corresponds to `into_iter` method
413                    ty::AssocKind::Fn { .. } => {
414                        // For methods, we check the function signature's return type for any GATs
415                        // to constrain. In the `into_iter` case, we see that the return type
416                        // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
417                        let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
418                            item_def_id.to_def_id(),
419                            tcx.fn_sig(item_def_id).instantiate_identity(),
420                        );
421                        gather_gat_bounds(
422                            tcx,
423                            param_env,
424                            item_def_id,
425                            sig.inputs_and_output,
426                            // We also assume that all of the function signature's parameter types
427                            // are well formed.
428                            &sig.inputs().iter().copied().collect(),
429                            gat_def_id,
430                            gat_generics,
431                        )
432                    }
433                    // In our example, this corresponds to the `Iter` and `Item` associated types
434                    ty::AssocKind::Type { .. } => {
435                        // If our associated item is a GAT with missing bounds, add them to
436                        // the param-env here. This allows this GAT to propagate missing bounds
437                        // to other GATs.
438                        let param_env = augment_param_env(
439                            tcx,
440                            param_env,
441                            required_bounds_by_item.get(&item_def_id),
442                        );
443                        gather_gat_bounds(
444                            tcx,
445                            param_env,
446                            item_def_id,
447                            tcx.explicit_item_bounds(item_def_id)
448                                .iter_identity_copied()
449                                .collect::<Vec<_>>(),
450                            &FxIndexSet::default(),
451                            gat_def_id,
452                            gat_generics,
453                        )
454                    }
455                    ty::AssocKind::Const { .. } => None,
456                };
457
458                if let Some(item_required_bounds) = item_required_bounds {
459                    // Take the intersection of the required bounds for this GAT, and
460                    // the item_required_bounds which are the ones implied by just
461                    // this item alone.
462                    // This is why we use an Option<_>, since we need to distinguish
463                    // the empty set of bounds from the _uninitialized_ set of bounds.
464                    if let Some(new_required_bounds) = &mut new_required_bounds {
465                        new_required_bounds.retain(|b| item_required_bounds.contains(b));
466                    } else {
467                        new_required_bounds = Some(item_required_bounds);
468                    }
469                }
470            }
471
472            if let Some(new_required_bounds) = new_required_bounds {
473                let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
474                if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
475                    // Iterate until our required_bounds no longer change
476                    // Since they changed here, we should continue the loop
477                    should_continue = true;
478                }
479            }
480        }
481        // We know that this loop will eventually halt, since we only set `should_continue` if the
482        // `required_bounds` for this item grows. Since we are not creating any new region or type
483        // variables, the set of all region and type bounds that we could ever insert are limited
484        // by the number of unique types and regions we observe in a given item.
485        if !should_continue {
486            break;
487        }
488    }
489
490    for (gat_def_id, required_bounds) in required_bounds_by_item {
491        // Don't suggest adding `Self: 'a` to a GAT that can't be named
492        if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
493            continue;
494        }
495
496        let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
497        {
    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:497",
                        "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(497u32),
                        ::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);
498        let param_env = tcx.param_env(gat_def_id);
499
500        let unsatisfied_bounds: Vec<_> = required_bounds
501            .into_iter()
502            .filter(|clause| match clause.kind().skip_binder() {
503                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
504                    !region_known_to_outlive(
505                        tcx,
506                        gat_def_id,
507                        param_env,
508                        &FxIndexSet::default(),
509                        a,
510                        b,
511                    )
512                }
513                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
514                    !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
515                }
516                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
517            })
518            .map(|clause| clause.to_string())
519            .collect();
520
521        if !unsatisfied_bounds.is_empty() {
522            let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
523            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!(
524                "{} {}",
525                gat_item_hir.generics.add_where_or_trailing_comma(),
526                unsatisfied_bounds.join(", "),
527            );
528            let bound =
529                if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
530            tcx.dcx()
531                .struct_span_err(
532                    gat_item_hir.span,
533                    ::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),
534                )
535                .with_span_suggestion(
536                    gat_item_hir.generics.tail_span_for_predicate_suggestion(),
537                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add the required where clause{0}",
                plural))
    })format!("add the required where clause{plural}"),
538                    suggestion,
539                    Applicability::MachineApplicable,
540                )
541                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
                bound))
    })format!(
542                    "{bound} currently required to ensure that impls have maximum flexibility"
543                ))
544                .with_note(
545                    "we are soliciting feedback, see issue #87479 \
546                     <https://github.com/rust-lang/rust/issues/87479> for more information",
547                )
548                .emit();
549        }
550    }
551}
552
553/// Add a new set of predicates to the caller_bounds of an existing param_env.
554fn augment_param_env<'tcx>(
555    tcx: TyCtxt<'tcx>,
556    param_env: ty::ParamEnv<'tcx>,
557    new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
558) -> ty::ParamEnv<'tcx> {
559    let Some(new_predicates) = new_predicates else {
560        return param_env;
561    };
562
563    if new_predicates.is_empty() {
564        return param_env;
565    }
566
567    let bounds = tcx.mk_clauses_from_iter(
568        param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
569    );
570    // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
571    // i.e. traits::normalize_param_env_or_error
572    ty::ParamEnv::new(bounds)
573}
574
575/// We use the following trait as an example throughout this function.
576/// Specifically, let's assume that `to_check` here is the return type
577/// of `into_iter`, and the GAT we are checking this for is `Iter`.
578/// ```rust,ignore (this code fails due to this lint)
579/// trait IntoIter {
580///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
581///     type Item<'a>;
582///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
583/// }
584/// ```
585fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
586    tcx: TyCtxt<'tcx>,
587    param_env: ty::ParamEnv<'tcx>,
588    item_def_id: LocalDefId,
589    to_check: T,
590    wf_tys: &FxIndexSet<Ty<'tcx>>,
591    gat_def_id: LocalDefId,
592    gat_generics: &'tcx ty::Generics,
593) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
594    // The bounds we that we would require from `to_check`
595    let mut bounds = FxIndexSet::default();
596
597    let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
598
599    // If both regions and types are empty, then this GAT isn't in the
600    // set of types we are checking, and we shouldn't try to do clause analysis
601    // (particularly, doing so would end up with an empty set of clauses,
602    // since the current method would require none, and we take the
603    // intersection of requirements of all methods)
604    if types.is_empty() && regions.is_empty() {
605        return None;
606    }
607
608    for (region_a, region_a_idx) in &regions {
609        // Ignore `'static` lifetimes for the purpose of this lint: it's
610        // because we know it outlives everything and so doesn't give meaningful
611        // clues. Also ignore `ReError`, to avoid knock-down errors.
612        if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
613            continue;
614        }
615        // For each region argument (e.g., `'a` in our example), check for a
616        // relationship to the type arguments (e.g., `Self`). If there is an
617        // outlives relationship (`Self: 'a`), then we want to ensure that is
618        // reflected in a where clause on the GAT itself.
619        for (ty, ty_idx) in &types {
620            // In our example, requires that `Self: 'a`
621            if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
622                {
    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:622",
                        "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(622u32),
                        ::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);
623                {
    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:623",
                        "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(623u32),
                        ::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}");
624                // Translate into the generic parameters of the GAT. In
625                // our example, the type was `Self`, which will also be
626                // `Self` in the GAT.
627                let ty_param = gat_generics.param_at(*ty_idx, tcx);
628                let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
629                // Same for the region. In our example, 'a corresponds
630                // to the 'me parameter.
631                let region_param = gat_generics.param_at(*region_a_idx, tcx);
632                let region_param = ty::Region::new_early_param(
633                    tcx,
634                    ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
635                );
636                // The predicate we expect to see. (In our example,
637                // `Self: 'me`.)
638                bounds.insert(
639                    ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
640                        .upcast(tcx),
641                );
642            }
643        }
644
645        // For each region argument (e.g., `'a` in our example), also check for a
646        // relationship to the other region arguments. If there is an outlives
647        // relationship, then we want to ensure that is reflected in the where clause
648        // on the GAT itself.
649        for (region_b, region_b_idx) in &regions {
650            // Again, skip `'static` because it outlives everything. Also, we trivially
651            // know that a region outlives itself. Also ignore `ReError`, to avoid
652            // knock-down errors.
653            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 {
654                continue;
655            }
656            if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
657                {
    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:657",
                        "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(657u32),
                        ::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);
658                {
    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:658",
                        "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(658u32),
                        ::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}");
659                // Translate into the generic parameters of the GAT.
660                let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
661                let region_a_param = ty::Region::new_early_param(
662                    tcx,
663                    ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
664                );
665                // Same for the region.
666                let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
667                let region_b_param = ty::Region::new_early_param(
668                    tcx,
669                    ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
670                );
671                // The predicate we expect to see.
672                bounds.insert(
673                    ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
674                        region_a_param,
675                        region_b_param,
676                    ))
677                    .upcast(tcx),
678                );
679            }
680        }
681    }
682
683    Some(bounds)
684}
685
686/// Given a known `param_env` and a set of well formed types, can we prove that
687/// `ty` outlives `region`.
688fn ty_known_to_outlive<'tcx>(
689    tcx: TyCtxt<'tcx>,
690    id: LocalDefId,
691    param_env: ty::ParamEnv<'tcx>,
692    wf_tys: &FxIndexSet<Ty<'tcx>>,
693    ty: Ty<'tcx>,
694    region: ty::Region<'tcx>,
695) -> bool {
696    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
697        infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
698            sub_region: region,
699            sup_type: ty,
700            origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
701        });
702    })
703}
704
705/// Given a known `param_env` and a set of well formed types, can we prove that
706/// `region_a` outlives `region_b`
707fn region_known_to_outlive<'tcx>(
708    tcx: TyCtxt<'tcx>,
709    id: LocalDefId,
710    param_env: ty::ParamEnv<'tcx>,
711    wf_tys: &FxIndexSet<Ty<'tcx>>,
712    region_a: ty::Region<'tcx>,
713    region_b: ty::Region<'tcx>,
714) -> bool {
715    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
716        infcx.sub_regions(
717            SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
718            region_b,
719            region_a,
720        );
721    })
722}
723
724/// Given a known `param_env` and a set of well formed types, set up an
725/// `InferCtxt`, call the passed function (to e.g. set up region constraints
726/// to be tested), then resolve region and return errors
727fn test_region_obligations<'tcx>(
728    tcx: TyCtxt<'tcx>,
729    id: LocalDefId,
730    param_env: ty::ParamEnv<'tcx>,
731    wf_tys: &FxIndexSet<Ty<'tcx>>,
732    add_constraints: impl FnOnce(&InferCtxt<'tcx>),
733) -> bool {
734    // Unfortunately, we have to use a new `InferCtxt` each call, because
735    // region constraints get added and solved there and we need to test each
736    // call individually.
737    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
738
739    add_constraints(&infcx);
740
741    let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
742    {
    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:742",
                        "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(742u32),
                        ::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");
743
744    // If we were able to prove that the type outlives the region without
745    // an error, it must be because of the implied or explicit bounds...
746    errors.is_empty()
747}
748
749/// TypeVisitor that looks for uses of GATs like
750/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
751/// the two vectors, `regions` and `types` (depending on their kind). For each
752/// parameter `Pi` also track the index `i`.
753struct GATArgsCollector<'tcx> {
754    gat: DefId,
755    // Which region appears and which parameter index its instantiated with
756    regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
757    // Which params appears and which parameter index its instantiated with
758    types: FxIndexSet<(Ty<'tcx>, usize)>,
759}
760
761impl<'tcx> GATArgsCollector<'tcx> {
762    fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
763        gat: DefId,
764        t: T,
765    ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
766        let mut visitor =
767            GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
768        t.visit_with(&mut visitor);
769        (visitor.regions, visitor.types)
770    }
771}
772
773impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
774    fn visit_ty(&mut self, t: Ty<'tcx>) {
775        match t.kind() {
776            &ty::Alias(p @ ty::AliasTy { kind: ty::Projection { def_id }, .. })
777                if def_id == self.gat =>
778            {
779                for (idx, arg) in p.args.iter().enumerate() {
780                    match arg.kind() {
781                        GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
782                            self.regions.insert((lt, idx));
783                        }
784                        GenericArgKind::Type(t) => {
785                            self.types.insert((t, idx));
786                        }
787                        _ => {}
788                    }
789                }
790            }
791            _ => {}
792        }
793        t.super_visit_with(self)
794    }
795}
796
797fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
798    let item_name = tcx.item_name(trait_item_def_id.to_def_id());
799    let trait_def_id = tcx.local_parent(trait_item_def_id);
800
801    let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
802        .skip(1)
803        .flat_map(|supertrait_def_id| {
804            tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
805        })
806        .collect();
807    if !shadowed.is_empty() {
808        let shadowee = if let [shadowed] = shadowed[..] {
809            errors::SupertraitItemShadowee::Labeled {
810                span: tcx.def_span(shadowed.def_id),
811                supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
812            }
813        } else {
814            let (traits, spans): (Vec<_>, Vec<_>) = shadowed
815                .iter()
816                .map(|item| {
817                    (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
818                })
819                .unzip();
820            errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
821        };
822
823        tcx.emit_node_span_lint(
824            SHADOWING_SUPERTRAIT_ITEMS,
825            tcx.local_def_id_to_hir_id(trait_item_def_id),
826            tcx.def_span(trait_item_def_id),
827            errors::SupertraitItemShadowing {
828                item: item_name,
829                subtrait: tcx.item_name(trait_def_id.to_def_id()),
830                shadowee,
831            },
832        );
833    }
834}
835
836fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
837    match param.kind {
838        // We currently only check wf of const params here.
839        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
840
841        // Const parameters are well formed if their type is structural match.
842        ty::GenericParamDefKind::Const { .. } => {
843            let ty = tcx.type_of(param.def_id).instantiate_identity();
844            let span = tcx.def_span(param.def_id);
845            let def_id = param.def_id.expect_local();
846
847            if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
848                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
849                    wfcx.register_bound(
850                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
851                        wfcx.param_env,
852                        ty,
853                        tcx.require_lang_item(LangItem::ConstParamTy, span),
854                    );
855                    Ok(())
856                })
857            } else {
858                let span = || {
859                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
860                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
861                    else {
862                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
863                    };
864                    span
865                };
866                let mut diag = match ty.kind() {
867                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
868                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
869                        span(),
870                        "using function pointers as const generic parameters is forbidden",
871                    ),
872                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
873                        span(),
874                        "using raw pointers as const generic parameters is forbidden",
875                    ),
876                    _ => {
877                        // Avoid showing "{type error}" to users. See #118179.
878                        ty.error_reported()?;
879
880                        tcx.dcx().struct_span_err(
881                            span(),
882                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
                ty))
    })format!(
883                                "`{ty}` is forbidden as the type of a const generic parameter",
884                            ),
885                        )
886                    }
887                };
888
889                diag.note("the only supported types are integers, `bool`, and `char`");
890
891                let cause = ObligationCause::misc(span(), def_id);
892                let adt_const_params_feature_string =
893                    " more complex and user defined types".to_string();
894                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
895                    tcx,
896                    tcx.param_env(param.def_id),
897                    ty,
898                    cause,
899                ) {
900                    // Can never implement `ConstParamTy`, don't suggest anything.
901                    Err(
902                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
903                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
904                    ) => None,
905                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
906                        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![
907                            (adt_const_params_feature_string, sym::adt_const_params),
908                            (
909                                " references to implement the `ConstParamTy` trait".into(),
910                                sym::unsized_const_params,
911                            ),
912                        ])
913                    }
914                    // May be able to implement `ConstParamTy`. Only emit the feature help
915                    // if the type is local, since the user may be able to fix the local type.
916                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
917                        fn ty_is_local(ty: Ty<'_>) -> bool {
918                            match ty.kind() {
919                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
920                                // Arrays and slices use the inner type's `ConstParamTy`.
921                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
922                                // `&` references use the inner type's `ConstParamTy`.
923                                // `&mut` are not supported.
924                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
925                                // Say that a tuple is local if any of its components are local.
926                                // This is not strictly correct, but it's likely that the user can fix the local component.
927                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
928                                _ => false,
929                            }
930                        }
931
932                        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![(
933                            adt_const_params_feature_string,
934                            sym::adt_const_params,
935                        )])
936                    }
937                    // Implements `ConstParamTy`, suggest adding the feature to enable.
938                    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)]),
939                };
940                if let Some(features) = may_suggest_feature {
941                    tcx.disabled_nightly_features(&mut diag, features);
942                }
943
944                Err(diag.emit())
945            }
946        }
947    }
948}
949
950#[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(950u32),
                                    ::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))]
951pub(crate) fn check_associated_item(
952    tcx: TyCtxt<'_>,
953    def_id: LocalDefId,
954) -> Result<(), ErrorGuaranteed> {
955    let loc = Some(WellFormedLoc::Ty(def_id));
956    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
957        let item = tcx.associated_item(def_id);
958
959        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
960        // other `Foo` impls are incoherent.
961        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
962
963        let self_ty = match item.container {
964            ty::AssocContainer::Trait => tcx.types.self_param,
965            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
966                tcx.type_of(item.container_id(tcx)).instantiate_identity()
967            }
968        };
969
970        let span = tcx.def_span(def_id);
971
972        match item.kind {
973            ty::AssocKind::Const { .. } => {
974                let ty = tcx.type_of(def_id).instantiate_identity();
975                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
976                wfcx.register_wf_obligation(span, loc, ty.into());
977
978                let has_value = item.defaultness(tcx).has_value();
979                if tcx.is_type_const(def_id) {
980                    check_type_const(wfcx, def_id, ty, has_value)?;
981                }
982
983                if has_value {
984                    let code = ObligationCauseCode::SizedConstOrStatic;
985                    wfcx.register_bound(
986                        ObligationCause::new(span, def_id, code),
987                        wfcx.param_env,
988                        ty,
989                        tcx.require_lang_item(LangItem::Sized, span),
990                    );
991                }
992
993                Ok(())
994            }
995            ty::AssocKind::Fn { .. } => {
996                let sig = tcx.fn_sig(def_id).instantiate_identity();
997                let hir_sig =
998                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
999                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1000                check_method_receiver(wfcx, hir_sig, item, self_ty)
1001            }
1002            ty::AssocKind::Type { .. } => {
1003                if let ty::AssocContainer::Trait = item.container {
1004                    check_associated_type_bounds(wfcx, item, span)
1005                }
1006                if item.defaultness(tcx).has_value() {
1007                    let ty = tcx.type_of(def_id).instantiate_identity();
1008                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1009                    wfcx.register_wf_obligation(span, loc, ty.into());
1010                }
1011                Ok(())
1012            }
1013        }
1014    })
1015}
1016
1017/// In a type definition, we check that to ensure that the types of the fields are well-formed.
1018fn check_type_defn<'tcx>(
1019    tcx: TyCtxt<'tcx>,
1020    item: &hir::Item<'tcx>,
1021    all_sized: bool,
1022) -> Result<(), ErrorGuaranteed> {
1023    tcx.ensure_ok().check_representability(item.owner_id.def_id);
1024    let adt_def = tcx.adt_def(item.owner_id);
1025
1026    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1027        let variants = adt_def.variants();
1028        let packed = adt_def.repr().packed();
1029
1030        for variant in variants.iter() {
1031            // All field types must be well-formed.
1032            for field in &variant.fields {
1033                if let Some(def_id) = field.value
1034                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1035                {
1036                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1037                    // be refactored to check the instantiate-ability of the code better.
1038                    if let Some(def_id) = def_id.as_local()
1039                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1040                        && let expr = &tcx.hir_body(anon.body).value
1041                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1042                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1043                    {
1044                        // Do not evaluate bare `const` params, as those would ICE and are only
1045                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1046                    } else {
1047                        // Evaluate the constant proactively, to emit an error if the constant has
1048                        // an unconditional error. We only do so if the const has no type params.
1049                        let _ = tcx.const_eval_poly(def_id);
1050                    }
1051                }
1052                let field_id = field.did.expect_local();
1053                let hir::FieldDef { ty: hir_ty, .. } =
1054                    tcx.hir_node_by_def_id(field_id).expect_field();
1055                let ty = wfcx.deeply_normalize(
1056                    hir_ty.span,
1057                    None,
1058                    tcx.type_of(field.did).instantiate_identity(),
1059                );
1060                wfcx.register_wf_obligation(
1061                    hir_ty.span,
1062                    Some(WellFormedLoc::Ty(field_id)),
1063                    ty.into(),
1064                );
1065
1066                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())
1067                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1068                {
1069                    // Scalable vectors can only be fields of structs if the type has a
1070                    // `rustc_scalable_vector` attribute w/out specifying an element count
1071                    tcx.dcx().span_err(
1072                        hir_ty.span,
1073                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1074                            "scalable vectors cannot be fields of a {}",
1075                            adt_def.variant_descr()
1076                        ),
1077                    );
1078                }
1079            }
1080
1081            // For DST, or when drop needs to copy things around, all
1082            // intermediate types must be sized.
1083            let needs_drop_copy = || {
1084                packed && {
1085                    let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1086                    let ty = tcx.erase_and_anonymize_regions(ty);
1087                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1088                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1089                }
1090            };
1091            // All fields (except for possibly the last) should be sized.
1092            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1093            let unsized_len = if all_sized { 0 } else { 1 };
1094            for (idx, field) in
1095                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1096            {
1097                let last = idx == variant.fields.len() - 1;
1098                let field_id = field.did.expect_local();
1099                let hir::FieldDef { ty: hir_ty, .. } =
1100                    tcx.hir_node_by_def_id(field_id).expect_field();
1101                let ty = wfcx.normalize(
1102                    hir_ty.span,
1103                    None,
1104                    tcx.type_of(field.did).instantiate_identity(),
1105                );
1106                wfcx.register_bound(
1107                    traits::ObligationCause::new(
1108                        hir_ty.span,
1109                        wfcx.body_def_id,
1110                        ObligationCauseCode::FieldSized {
1111                            adt_kind: match &item.kind {
1112                                ItemKind::Struct(..) => AdtKind::Struct,
1113                                ItemKind::Union(..) => AdtKind::Union,
1114                                ItemKind::Enum(..) => AdtKind::Enum,
1115                                kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
    format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1116                                    item.span,
1117                                    "should be wfchecking an ADT, got {kind:?}"
1118                                ),
1119                            },
1120                            span: hir_ty.span,
1121                            last,
1122                        },
1123                    ),
1124                    wfcx.param_env,
1125                    ty,
1126                    tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1127                );
1128            }
1129
1130            // Explicit `enum` discriminant values must const-evaluate successfully.
1131            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1132                match tcx.const_eval_poly(discr_def_id) {
1133                    Ok(_) => {}
1134                    Err(ErrorHandled::Reported(..)) => {}
1135                    Err(ErrorHandled::TooGeneric(sp)) => {
1136                        ::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")
1137                    }
1138                }
1139            }
1140        }
1141
1142        check_where_clauses(wfcx, item.owner_id.def_id);
1143        Ok(())
1144    })
1145}
1146
1147#[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(1147u32),
                                    ::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:1149",
                                    "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(1149u32),
                                    ::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))]
1148fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1149    debug!(?item.owner_id);
1150
1151    let def_id = item.owner_id.def_id;
1152    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1153        // `PointeeSized` is removed during lowering.
1154        return Ok(());
1155    }
1156
1157    let trait_def = tcx.trait_def(def_id);
1158    if trait_def.is_marker
1159        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1160    {
1161        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1162            struct_span_code_err!(
1163                tcx.dcx(),
1164                tcx.def_span(*associated_def_id),
1165                E0714,
1166                "marker traits cannot have associated items",
1167            )
1168            .emit();
1169        }
1170    }
1171
1172    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1173        check_where_clauses(wfcx, def_id);
1174        Ok(())
1175    });
1176
1177    // Only check traits, don't check trait aliases
1178    if let hir::ItemKind::Trait(..) = item.kind {
1179        check_gat_where_clauses(tcx, item.owner_id.def_id);
1180    }
1181    res
1182}
1183
1184/// Checks all associated type defaults of trait `trait_def_id`.
1185///
1186/// Assuming the defaults are used, check that all predicates (bounds on the
1187/// assoc type and where clauses on the trait) hold.
1188fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1189    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1190
1191    {
    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:1191",
                        "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(1191u32),
                        ::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);
1192    let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1193        traits::wf::clause_obligations(
1194            wfcx.infcx,
1195            wfcx.param_env,
1196            wfcx.body_def_id,
1197            bound,
1198            bound_span,
1199        )
1200    });
1201
1202    wfcx.register_obligations(wf_obligations);
1203}
1204
1205fn check_item_fn(
1206    tcx: TyCtxt<'_>,
1207    def_id: LocalDefId,
1208    decl: &hir::FnDecl<'_>,
1209) -> Result<(), ErrorGuaranteed> {
1210    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1211        check_eiis(tcx, def_id);
1212
1213        let sig = tcx.fn_sig(def_id).instantiate_identity();
1214        check_fn_or_method(wfcx, sig, decl, def_id);
1215        Ok(())
1216    })
1217}
1218
1219fn check_eiis(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1220    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1221    // that was used to mark the implementation. This is a two step process.
1222    for EiiImpl { resolution, span, .. } in
1223        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[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()
1224    {
1225        let (foreign_item, name) = match resolution {
1226            EiiImplResolution::Macro(def_id) => {
1227                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1228                // signature that we'd like to compare the function we're currently checking with
1229                if let Some(foreign_item) =
1230                    {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(*def_id, &tcx) {
                #[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)
1231                {
1232                    (foreign_item, tcx.item_name(*def_id))
1233                } else {
1234                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1235                    continue;
1236                }
1237            }
1238            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1239            EiiImplResolution::Error(_eg) => continue,
1240        };
1241
1242        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1243    }
1244}
1245
1246#[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(1246u32),
                                    ::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))]
1247pub(crate) fn check_static_item<'tcx>(
1248    tcx: TyCtxt<'tcx>,
1249    item_id: LocalDefId,
1250    ty: Ty<'tcx>,
1251    should_check_for_sync: bool,
1252) -> Result<(), ErrorGuaranteed> {
1253    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1254        let span = tcx.ty_span(item_id);
1255        let loc = Some(WellFormedLoc::Ty(item_id));
1256        let item_ty = wfcx.deeply_normalize(span, loc, ty);
1257
1258        let is_foreign_item = tcx.is_foreign_item(item_id);
1259        let is_structurally_foreign_item = || {
1260            let tail = tcx.struct_tail_raw(
1261                item_ty,
1262                &ObligationCause::dummy(),
1263                |ty| wfcx.deeply_normalize(span, loc, ty),
1264                || {},
1265            );
1266
1267            matches!(tail.kind(), ty::Foreign(_))
1268        };
1269        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1270
1271        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1272        if forbid_unsized {
1273            let span = tcx.def_span(item_id);
1274            wfcx.register_bound(
1275                traits::ObligationCause::new(
1276                    span,
1277                    wfcx.body_def_id,
1278                    ObligationCauseCode::SizedConstOrStatic,
1279                ),
1280                wfcx.param_env,
1281                item_ty,
1282                tcx.require_lang_item(LangItem::Sized, span),
1283            );
1284        }
1285
1286        // Ensure that the end result is `Sync` in a non-thread local `static`.
1287        let should_check_for_sync = should_check_for_sync
1288            && !is_foreign_item
1289            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1290            && !tcx.is_thread_local_static(item_id.to_def_id());
1291
1292        if should_check_for_sync {
1293            wfcx.register_bound(
1294                traits::ObligationCause::new(
1295                    span,
1296                    wfcx.body_def_id,
1297                    ObligationCauseCode::SharedStatic,
1298                ),
1299                wfcx.param_env,
1300                item_ty,
1301                tcx.require_lang_item(LangItem::Sync, span),
1302            );
1303        }
1304        Ok(())
1305    })
1306}
1307
1308#[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(1308u32),
                                    ::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))]
1309pub(super) fn check_type_const<'tcx>(
1310    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1311    def_id: LocalDefId,
1312    item_ty: Ty<'tcx>,
1313    has_value: bool,
1314) -> Result<(), ErrorGuaranteed> {
1315    let tcx = wfcx.tcx();
1316    let span = tcx.def_span(def_id);
1317
1318    wfcx.register_bound(
1319        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1320        wfcx.param_env,
1321        item_ty,
1322        tcx.require_lang_item(LangItem::ConstParamTy, span),
1323    );
1324
1325    if has_value {
1326        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1327        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1328        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1329
1330        wfcx.register_obligation(Obligation::new(
1331            tcx,
1332            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1333            wfcx.param_env,
1334            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1335        ));
1336    }
1337    Ok(())
1338}
1339
1340#[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(1340u32),
                                    ::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:1412",
                                                        "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(1412u32),
                                                        ::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_))]
1341fn check_impl<'tcx>(
1342    tcx: TyCtxt<'tcx>,
1343    item: &'tcx hir::Item<'tcx>,
1344    impl_: &hir::Impl<'_>,
1345) -> Result<(), ErrorGuaranteed> {
1346    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1347        match impl_.of_trait {
1348            Some(of_trait) => {
1349                // `#[rustc_reservation_impl]` impls are not real impls and
1350                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1351                // won't hold).
1352                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1353                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1354                // case other `Foo` impls are incoherent.
1355                tcx.ensure_result().coherent_trait(trait_ref.def_id)?;
1356                let trait_span = of_trait.trait_ref.path.span;
1357                let trait_ref = wfcx.deeply_normalize(
1358                    trait_span,
1359                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1360                    trait_ref,
1361                );
1362                let trait_pred =
1363                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1364                let mut obligations = traits::wf::trait_obligations(
1365                    wfcx.infcx,
1366                    wfcx.param_env,
1367                    wfcx.body_def_id,
1368                    trait_pred,
1369                    trait_span,
1370                    item,
1371                );
1372                for obligation in &mut obligations {
1373                    if obligation.cause.span != trait_span {
1374                        // We already have a better span.
1375                        continue;
1376                    }
1377                    if let Some(pred) = obligation.predicate.as_trait_clause()
1378                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1379                    {
1380                        obligation.cause.span = impl_.self_ty.span;
1381                    }
1382                    if let Some(pred) = obligation.predicate.as_projection_clause()
1383                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1384                    {
1385                        obligation.cause.span = impl_.self_ty.span;
1386                    }
1387                }
1388
1389                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1390                if tcx.is_conditionally_const(item.owner_id.def_id) {
1391                    for (bound, _) in
1392                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1393                    {
1394                        let bound = wfcx.normalize(
1395                            item.span,
1396                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1397                            bound,
1398                        );
1399                        wfcx.register_obligation(Obligation::new(
1400                            tcx,
1401                            ObligationCause::new(
1402                                impl_.self_ty.span,
1403                                wfcx.body_def_id,
1404                                ObligationCauseCode::WellFormed(None),
1405                            ),
1406                            wfcx.param_env,
1407                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1408                        ))
1409                    }
1410                }
1411
1412                debug!(?obligations);
1413                wfcx.register_obligations(obligations);
1414            }
1415            None => {
1416                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1417                let self_ty = wfcx.deeply_normalize(
1418                    item.span,
1419                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1420                    self_ty,
1421                );
1422                wfcx.register_wf_obligation(
1423                    impl_.self_ty.span,
1424                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1425                    self_ty.into(),
1426                );
1427            }
1428        }
1429
1430        check_where_clauses(wfcx, item.owner_id.def_id);
1431        Ok(())
1432    })
1433}
1434
1435/// Checks where-clauses and inline bounds that are declared on `def_id`.
1436#[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(1436u32),
                                    ::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))]
1437pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1438    let infcx = wfcx.infcx;
1439    let tcx = wfcx.tcx();
1440
1441    let predicates = tcx.predicates_of(def_id.to_def_id());
1442    let generics = tcx.generics_of(def_id);
1443
1444    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1445    // For example, this forbids the declaration:
1446    //
1447    //     struct Foo<T = Vec<[u32]>> { .. }
1448    //
1449    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1450    for param in &generics.own_params {
1451        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1452            // Ignore dependent defaults -- that is, where the default of one type
1453            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1454            // be sure if it will error or not as user might always specify the other.
1455            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1456            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1457            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1458            if !default.has_param() {
1459                wfcx.register_wf_obligation(
1460                    tcx.def_span(param.def_id),
1461                    matches!(param.kind, GenericParamDefKind::Type { .. })
1462                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1463                    default.as_term().unwrap(),
1464                );
1465            } else {
1466                // If we've got a generic const parameter we still want to check its
1467                // type is correct in case both it and the param type are fully concrete.
1468                let GenericArgKind::Const(ct) = default.kind() else {
1469                    continue;
1470                };
1471
1472                let ct_ty = match ct.kind() {
1473                    ty::ConstKind::Infer(_)
1474                    | ty::ConstKind::Placeholder(_)
1475                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1476                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1477                    ty::ConstKind::Value(cv) => cv.ty,
1478                    ty::ConstKind::Unevaluated(uv) => {
1479                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1480                    }
1481                    ty::ConstKind::Param(param_ct) => {
1482                        param_ct.find_const_ty_from_env(wfcx.param_env)
1483                    }
1484                };
1485
1486                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1487                if !ct_ty.has_param() && !param_ty.has_param() {
1488                    let cause = traits::ObligationCause::new(
1489                        tcx.def_span(param.def_id),
1490                        wfcx.body_def_id,
1491                        ObligationCauseCode::WellFormed(None),
1492                    );
1493                    wfcx.register_obligation(Obligation::new(
1494                        tcx,
1495                        cause,
1496                        wfcx.param_env,
1497                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1498                    ));
1499                }
1500            }
1501        }
1502    }
1503
1504    // Check that trait predicates are WF when params are instantiated with their defaults.
1505    // We don't want to overly constrain the predicates that may be written but we want to
1506    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1507    // Therefore we check if a predicate which contains a single type param
1508    // with a concrete default is WF with that default instantiated.
1509    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1510    //
1511    // First we build the defaulted generic parameters.
1512    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1513        if param.index >= generics.parent_count as u32
1514            // If the param has a default, ...
1515            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1516            // ... and it's not a dependent default, ...
1517            && !default.has_param()
1518        {
1519            // ... then instantiate it with the default.
1520            return default;
1521        }
1522        tcx.mk_param_from_def(param)
1523    });
1524
1525    // Now we build the instantiated predicates.
1526    let default_obligations = predicates
1527        .predicates
1528        .iter()
1529        .flat_map(|&(pred, sp)| {
1530            #[derive(Default)]
1531            struct CountParams {
1532                params: FxHashSet<u32>,
1533            }
1534            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1535                type Result = ControlFlow<()>;
1536                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1537                    if let ty::Param(param) = t.kind() {
1538                        self.params.insert(param.index);
1539                    }
1540                    t.super_visit_with(self)
1541                }
1542
1543                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1544                    ControlFlow::Break(())
1545                }
1546
1547                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1548                    if let ty::ConstKind::Param(param) = c.kind() {
1549                        self.params.insert(param.index);
1550                    }
1551                    c.super_visit_with(self)
1552                }
1553            }
1554            let mut param_count = CountParams::default();
1555            let has_region = pred.visit_with(&mut param_count).is_break();
1556            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1557            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1558            // or preds with multiple params.
1559            if instantiated_pred.has_non_region_param()
1560                || param_count.params.len() > 1
1561                || has_region
1562            {
1563                None
1564            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1565                // Avoid duplication of predicates that contain no parameters, for example.
1566                None
1567            } else {
1568                Some((instantiated_pred, sp))
1569            }
1570        })
1571        .map(|(pred, sp)| {
1572            // Convert each of those into an obligation. So if you have
1573            // something like `struct Foo<T: Copy = String>`, we would
1574            // take that predicate `T: Copy`, instantiated with `String: Copy`
1575            // (actually that happens in the previous `flat_map` call),
1576            // and then try to prove it (in this case, we'll fail).
1577            //
1578            // Note the subtle difference from how we handle `predicates`
1579            // below: there, we are not trying to prove those predicates
1580            // to be *true* but merely *well-formed*.
1581            let pred = wfcx.normalize(sp, None, pred);
1582            let cause = traits::ObligationCause::new(
1583                sp,
1584                wfcx.body_def_id,
1585                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1586            );
1587            Obligation::new(tcx, cause, wfcx.param_env, pred)
1588        });
1589
1590    let predicates = predicates.instantiate_identity(tcx);
1591
1592    let assoc_const_obligations: Vec<_> = predicates
1593        .predicates
1594        .iter()
1595        .copied()
1596        .zip(predicates.spans.iter().copied())
1597        .filter_map(|(clause, sp)| {
1598            let proj = clause.as_projection_clause()?;
1599            let pred_binder = proj
1600                .map_bound(|pred| {
1601                    pred.term.as_const().map(|ct| {
1602                        let assoc_const_ty = tcx
1603                            .type_of(pred.projection_term.def_id)
1604                            .instantiate(tcx, pred.projection_term.args);
1605                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1606                    })
1607                })
1608                .transpose();
1609            pred_binder.map(|pred_binder| {
1610                let cause = traits::ObligationCause::new(
1611                    sp,
1612                    wfcx.body_def_id,
1613                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1614                );
1615                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1616            })
1617        })
1618        .collect();
1619
1620    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1621    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1622        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1623    });
1624    let obligations: Vec<_> =
1625        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1626    wfcx.register_obligations(obligations);
1627}
1628
1629#[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(1629u32),
                                    ::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))]
1630fn check_fn_or_method<'tcx>(
1631    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1632    sig: ty::PolyFnSig<'tcx>,
1633    hir_decl: &hir::FnDecl<'_>,
1634    def_id: LocalDefId,
1635) {
1636    let tcx = wfcx.tcx();
1637    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1638
1639    // Normalize the input and output types one at a time, using a different
1640    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1641    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1642    // for each type, preventing the HIR wf check from generating
1643    // a nice error message.
1644    let arg_span =
1645        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1646
1647    sig.inputs_and_output =
1648        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1649            wfcx.deeply_normalize(
1650                arg_span(idx),
1651                Some(WellFormedLoc::Param {
1652                    function: def_id,
1653                    // Note that the `param_idx` of the output type is
1654                    // one greater than the index of the last input type.
1655                    param_idx: idx,
1656                }),
1657                ty,
1658            )
1659        }));
1660
1661    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1662        wfcx.register_wf_obligation(
1663            arg_span(idx),
1664            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1665            ty.into(),
1666        );
1667    }
1668
1669    check_where_clauses(wfcx, def_id);
1670
1671    if sig.abi == ExternAbi::RustCall {
1672        let span = tcx.def_span(def_id);
1673        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1674        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1675        // Check that the argument is a tuple and is sized
1676        if let Some(ty) = inputs.next() {
1677            wfcx.register_bound(
1678                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1679                wfcx.param_env,
1680                *ty,
1681                tcx.require_lang_item(hir::LangItem::Tuple, span),
1682            );
1683            wfcx.register_bound(
1684                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1685                wfcx.param_env,
1686                *ty,
1687                tcx.require_lang_item(hir::LangItem::Sized, span),
1688            );
1689        } else {
1690            tcx.dcx().span_err(
1691                hir_decl.inputs.last().map_or(span, |input| input.span),
1692                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1693            );
1694        }
1695        // No more inputs other than the `self` type and the tuple type
1696        if inputs.next().is_some() {
1697            tcx.dcx().span_err(
1698                hir_decl.inputs.last().map_or(span, |input| input.span),
1699                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1700            );
1701        }
1702    }
1703
1704    // If the function has a body, additionally require that the return type is sized.
1705    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1706        let span = match hir_decl.output {
1707            hir::FnRetTy::Return(ty) => ty.span,
1708            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1709        };
1710
1711        wfcx.register_bound(
1712            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1713            wfcx.param_env,
1714            sig.output(),
1715            tcx.require_lang_item(LangItem::Sized, span),
1716        );
1717    }
1718}
1719
1720/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1721#[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)]
1722enum ArbitrarySelfTypesLevel {
1723    Basic,        // just arbitrary_self_types
1724    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1725}
1726
1727#[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(1727u32),
                                    ::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:1747",
                                    "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(1747u32),
                                    ::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))]
1728fn check_method_receiver<'tcx>(
1729    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1730    fn_sig: &hir::FnSig<'_>,
1731    method: ty::AssocItem,
1732    self_ty: Ty<'tcx>,
1733) -> Result<(), ErrorGuaranteed> {
1734    let tcx = wfcx.tcx();
1735
1736    if !method.is_method() {
1737        return Ok(());
1738    }
1739
1740    let span = fn_sig.decl.inputs[0].span;
1741    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1742
1743    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1744    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1745    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1746
1747    debug!("check_method_receiver: sig={:?}", sig);
1748
1749    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1750
1751    let receiver_ty = sig.inputs()[0];
1752    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1753
1754    // If the receiver already has errors reported, consider it valid to avoid
1755    // unnecessary errors (#58712).
1756    receiver_ty.error_reported()?;
1757
1758    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1759        Some(ArbitrarySelfTypesLevel::WithPointers)
1760    } else if tcx.features().arbitrary_self_types() {
1761        Some(ArbitrarySelfTypesLevel::Basic)
1762    } else {
1763        None
1764    };
1765    let generics = tcx.generics_of(method.def_id);
1766
1767    let receiver_validity =
1768        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1769    if let Err(receiver_validity_err) = receiver_validity {
1770        return Err(match arbitrary_self_types_level {
1771            // Wherever possible, emit a message advising folks that the features
1772            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1773            // have helped.
1774            None if receiver_is_valid(
1775                wfcx,
1776                span,
1777                receiver_ty,
1778                self_ty,
1779                Some(ArbitrarySelfTypesLevel::Basic),
1780                generics,
1781            )
1782            .is_ok() =>
1783            {
1784                // Report error; would have worked with `arbitrary_self_types`.
1785                feature_err(
1786                    &tcx.sess,
1787                    sym::arbitrary_self_types,
1788                    span,
1789                    format!(
1790                        "`{receiver_ty}` cannot be used as the type of `self` without \
1791                            the `arbitrary_self_types` feature",
1792                    ),
1793                )
1794                .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>`"))
1795                .emit()
1796            }
1797            None | Some(ArbitrarySelfTypesLevel::Basic)
1798                if receiver_is_valid(
1799                    wfcx,
1800                    span,
1801                    receiver_ty,
1802                    self_ty,
1803                    Some(ArbitrarySelfTypesLevel::WithPointers),
1804                    generics,
1805                )
1806                .is_ok() =>
1807            {
1808                // Report error; would have worked with `arbitrary_self_types_pointers`.
1809                feature_err(
1810                    &tcx.sess,
1811                    sym::arbitrary_self_types_pointers,
1812                    span,
1813                    format!(
1814                        "`{receiver_ty}` cannot be used as the type of `self` without \
1815                            the `arbitrary_self_types_pointers` feature",
1816                    ),
1817                )
1818                .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>`"))
1819                .emit()
1820            }
1821            _ =>
1822            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1823            {
1824                match receiver_validity_err {
1825                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1826                        let hint = match receiver_ty
1827                            .builtin_deref(false)
1828                            .unwrap_or(receiver_ty)
1829                            .ty_adt_def()
1830                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1831                        {
1832                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1833                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1834                            _ => None,
1835                        };
1836
1837                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1838                    }
1839                    ReceiverValidityError::DoesNotDeref => {
1840                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1841                            span,
1842                            receiver_ty,
1843                        })
1844                    }
1845                    ReceiverValidityError::MethodGenericParamUsed => {
1846                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1847                    }
1848                }
1849            }
1850        });
1851    }
1852    Ok(())
1853}
1854
1855/// Error cases which may be returned from `receiver_is_valid`. These error
1856/// cases are generated in this function as they may be unearthed as we explore
1857/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1858enum ReceiverValidityError {
1859    /// The self type does not get to the receiver type by following the
1860    /// autoderef chain.
1861    DoesNotDeref,
1862    /// A type was found which is a method type parameter, and that's not allowed.
1863    MethodGenericParamUsed,
1864}
1865
1866/// Confirms that a type is not a type parameter referring to one of the
1867/// method's type params.
1868fn confirm_type_is_not_a_method_generic_param(
1869    ty: Ty<'_>,
1870    method_generics: &ty::Generics,
1871) -> Result<(), ReceiverValidityError> {
1872    if let ty::Param(param) = ty.kind() {
1873        if (param.index as usize) >= method_generics.parent_count {
1874            return Err(ReceiverValidityError::MethodGenericParamUsed);
1875        }
1876    }
1877    Ok(())
1878}
1879
1880/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1881/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1882/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1883/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1884/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1885///
1886/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1887/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1888/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1889fn receiver_is_valid<'tcx>(
1890    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1891    span: Span,
1892    receiver_ty: Ty<'tcx>,
1893    self_ty: Ty<'tcx>,
1894    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1895    method_generics: &ty::Generics,
1896) -> Result<(), ReceiverValidityError> {
1897    let infcx = wfcx.infcx;
1898    let tcx = wfcx.tcx();
1899    let cause =
1900        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1901
1902    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1903    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1904        let ocx = ObligationCtxt::new(wfcx.infcx);
1905        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1906        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1907            Ok(())
1908        } else {
1909            Err(NoSolution)
1910        }
1911    }) {
1912        return Ok(());
1913    }
1914
1915    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1916
1917    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1918
1919    // The `arbitrary_self_types` feature allows custom smart pointer
1920    // types to be method receivers, as identified by following the Receiver<Target=T>
1921    // chain.
1922    if arbitrary_self_types_enabled.is_some() {
1923        autoderef = autoderef.use_receiver_trait();
1924    }
1925
1926    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1927    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1928        autoderef = autoderef.include_raw_pointers();
1929    }
1930
1931    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1932    while let Some((potential_self_ty, _)) = autoderef.next() {
1933        {
    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:1933",
                        "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(1933u32),
                        ::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!(
1934            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1935            potential_self_ty, self_ty
1936        );
1937
1938        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1939
1940        // Check if the self type unifies. If it does, then commit the result
1941        // since it may have region side-effects.
1942        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1943            let ocx = ObligationCtxt::new(wfcx.infcx);
1944            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1945            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1946                Ok(())
1947            } else {
1948                Err(NoSolution)
1949            }
1950        }) {
1951            wfcx.register_obligations(autoderef.into_obligations());
1952            return Ok(());
1953        }
1954
1955        // Without `feature(arbitrary_self_types)`, we require that each step in the
1956        // deref chain implement `LegacyReceiver`.
1957        if arbitrary_self_types_enabled.is_none() {
1958            let legacy_receiver_trait_def_id =
1959                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1960            if !legacy_receiver_is_implemented(
1961                wfcx,
1962                legacy_receiver_trait_def_id,
1963                cause.clone(),
1964                potential_self_ty,
1965            ) {
1966                // We cannot proceed.
1967                break;
1968            }
1969
1970            // Register the bound, in case it has any region side-effects.
1971            wfcx.register_bound(
1972                cause.clone(),
1973                wfcx.param_env,
1974                potential_self_ty,
1975                legacy_receiver_trait_def_id,
1976            );
1977        }
1978    }
1979
1980    {
    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:1980",
                        "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(1980u32),
                        ::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);
1981    Err(ReceiverValidityError::DoesNotDeref)
1982}
1983
1984fn legacy_receiver_is_implemented<'tcx>(
1985    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1986    legacy_receiver_trait_def_id: DefId,
1987    cause: ObligationCause<'tcx>,
1988    receiver_ty: Ty<'tcx>,
1989) -> bool {
1990    let tcx = wfcx.tcx();
1991    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1992
1993    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1994
1995    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1996        true
1997    } else {
1998        {
    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:1998",
                        "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(1998u32),
                        ::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!(
1999            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2000            receiver_ty
2001        );
2002        false
2003    }
2004}
2005
2006pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2007    match tcx.def_kind(def_id) {
2008        DefKind::Enum | DefKind::Struct | DefKind::Union => {
2009            // Ok
2010        }
2011        DefKind::TyAlias => {
2012            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!(
2013                tcx.type_alias_is_lazy(def_id),
2014                "should not be computing variance of non-free type alias"
2015            );
2016        }
2017        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:?}"),
2018    }
2019
2020    let ty_predicates = tcx.predicates_of(def_id);
2021    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);
2022    let variances = tcx.variances_of(def_id);
2023
2024    let mut constrained_parameters: FxHashSet<_> = variances
2025        .iter()
2026        .enumerate()
2027        .filter(|&(_, &variance)| variance != ty::Bivariant)
2028        .map(|(index, _)| Parameter(index as u32))
2029        .collect();
2030
2031    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2032
2033    // Lazily calculated because it is only needed in case of an error.
2034    let explicitly_bounded_params = LazyCell::new(|| {
2035        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2036        tcx.hir_node_by_def_id(def_id)
2037            .generics()
2038            .unwrap()
2039            .predicates
2040            .iter()
2041            .filter_map(|predicate| match predicate.kind {
2042                hir::WherePredicateKind::BoundPredicate(predicate) => {
2043                    match icx.lower_ty(predicate.bounded_ty).kind() {
2044                        ty::Param(data) => Some(Parameter(data.index)),
2045                        _ => None,
2046                    }
2047                }
2048                _ => None,
2049            })
2050            .collect::<FxHashSet<_>>()
2051    });
2052
2053    for (index, _) in variances.iter().enumerate() {
2054        let parameter = Parameter(index as u32);
2055
2056        if constrained_parameters.contains(&parameter) {
2057            continue;
2058        }
2059
2060        let node = tcx.hir_node_by_def_id(def_id);
2061        let item = node.expect_item();
2062        let hir_generics = node.generics().unwrap();
2063        let hir_param = &hir_generics.params[index];
2064
2065        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2066
2067        if ty_param.def_id != hir_param.def_id.into() {
2068            // Valid programs always have lifetimes before types in the generic parameter list.
2069            // ty_generics are normalized to be in this required order, and variances are built
2070            // from ty generics, not from hir generics. but we need hir generics to get
2071            // a span out.
2072            //
2073            // If they aren't in the same order, then the user has written invalid code, and already
2074            // got an error about it (or I'm wrong about this).
2075            tcx.dcx().span_delayed_bug(
2076                hir_param.span,
2077                "hir generics and ty generics in different order",
2078            );
2079            continue;
2080        }
2081
2082        // Look for `ErrorGuaranteed` deeply within this type.
2083        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2084            .type_of(def_id)
2085            .instantiate_identity()
2086            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2087        {
2088            continue;
2089        }
2090
2091        match hir_param.name {
2092            hir::ParamName::Error(_) => {
2093                // Don't report a bivariance error for a lifetime that isn't
2094                // even valid to name.
2095            }
2096            _ => {
2097                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2098                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2099            }
2100        }
2101    }
2102}
2103
2104/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2105struct HasErrorDeep<'tcx> {
2106    tcx: TyCtxt<'tcx>,
2107    seen: FxHashSet<DefId>,
2108}
2109impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2110    type Result = ControlFlow<ErrorGuaranteed>;
2111
2112    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2113        match *ty.kind() {
2114            ty::Adt(def, _) => {
2115                if self.seen.insert(def.did()) {
2116                    for field in def.all_fields() {
2117                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2118                    }
2119                }
2120            }
2121            ty::Error(guar) => return ControlFlow::Break(guar),
2122            _ => {}
2123        }
2124        ty.super_visit_with(self)
2125    }
2126
2127    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2128        if let Err(guar) = r.error_reported() {
2129            ControlFlow::Break(guar)
2130        } else {
2131            ControlFlow::Continue(())
2132        }
2133    }
2134
2135    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2136        if let Err(guar) = c.error_reported() {
2137            ControlFlow::Break(guar)
2138        } else {
2139            ControlFlow::Continue(())
2140        }
2141    }
2142}
2143
2144fn report_bivariance<'tcx>(
2145    tcx: TyCtxt<'tcx>,
2146    param: &'tcx hir::GenericParam<'tcx>,
2147    has_explicit_bounds: bool,
2148    item: &'tcx hir::Item<'tcx>,
2149) -> ErrorGuaranteed {
2150    let param_name = param.name.ident();
2151
2152    let help = match item.kind {
2153        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2154            if let Some(def_id) = tcx.lang_items().phantom_data() {
2155                errors::UnusedGenericParameterHelp::Adt {
2156                    param_name,
2157                    phantom_data: tcx.def_path_str(def_id),
2158                }
2159            } else {
2160                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2161            }
2162        }
2163        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2164        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:?}"),
2165    };
2166
2167    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2168    intravisit::walk_item(
2169        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2170        item,
2171    );
2172
2173    if !usage_spans.is_empty() {
2174        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2175        // not actually looking into substitutions, just walking through fields / the "RHS".
2176        // We don't recurse into the hidden types of opaques or anything else fancy.
2177        let item_def_id = item.owner_id.to_def_id();
2178        let is_probably_cyclical =
2179            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2180                .visit_def(item_def_id)
2181                .is_break();
2182        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2183        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2184        // alias, and we should call those parameter usages recursive rather than just saying
2185        // they're unused...
2186        //
2187        // We currently report *all* of the parameter usages, since computing the exact
2188        // subset is very involved, and the fact we're mentioning recursion at all is
2189        // likely to guide the user in the right direction.
2190        if is_probably_cyclical {
2191            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2192                spans: usage_spans,
2193                param_span: param.span,
2194                param_name,
2195                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2196                help,
2197                note: (),
2198            });
2199        }
2200    }
2201
2202    let const_param_help =
2203        #[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);
2204
2205    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2206        span: param.span,
2207        param_name,
2208        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2209        usage_spans,
2210        help,
2211        const_param_help,
2212    });
2213    diag.code(E0392);
2214    if item.kind.recovered() {
2215        // Silence potentially redundant error, as the item had a parse error.
2216        diag.delay_as_bug()
2217    } else {
2218        diag.emit()
2219    }
2220}
2221
2222/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2223/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2224/// cyclical.
2225///
2226/// Notably, we don't consider substitutions here, so this may have false positives.
2227struct IsProbablyCyclical<'tcx> {
2228    tcx: TyCtxt<'tcx>,
2229    item_def_id: DefId,
2230    seen: FxHashSet<DefId>,
2231}
2232
2233impl<'tcx> IsProbablyCyclical<'tcx> {
2234    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2235        match self.tcx.def_kind(def_id) {
2236            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2237                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2238                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2239                })
2240            }
2241            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2242                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2243            }
2244            _ => ControlFlow::Continue(()),
2245        }
2246    }
2247}
2248
2249impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2250    type Result = ControlFlow<(), ()>;
2251
2252    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2253        let def_id = match ty.kind() {
2254            ty::Adt(adt_def, _) => Some(adt_def.did()),
2255            &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, .. }) => Some(def_id),
2256            _ => None,
2257        };
2258        if let Some(def_id) = def_id {
2259            if def_id == self.item_def_id {
2260                return ControlFlow::Break(());
2261            }
2262            if self.seen.insert(def_id) {
2263                self.visit_def(def_id)?;
2264            }
2265        }
2266        ty.super_visit_with(self)
2267    }
2268}
2269
2270/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2271///
2272/// This is used to report places where the user has used parameters in a
2273/// non-variance-constraining way for better bivariance errors.
2274struct CollectUsageSpans<'a> {
2275    spans: &'a mut Vec<Span>,
2276    param_def_id: DefId,
2277}
2278
2279impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2280    type Result = ();
2281
2282    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2283        // Skip the generics. We only care about fields, not where clause/param bounds.
2284    }
2285
2286    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2287        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2288            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2289                && def_id == self.param_def_id
2290            {
2291                self.spans.push(t.span);
2292                return;
2293            } else if let Res::SelfTyAlias { .. } = qpath.res {
2294                self.spans.push(t.span);
2295                return;
2296            }
2297        }
2298        intravisit::walk_ty(self, t);
2299    }
2300}
2301
2302impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2303    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2304    /// aren't true.
2305    #[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(2305u32),
                                    ::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))]
2306    fn check_false_global_bounds(&mut self) {
2307        let tcx = self.ocx.infcx.tcx;
2308        let mut span = tcx.def_span(self.body_def_id);
2309        let empty_env = ty::ParamEnv::empty();
2310
2311        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2312        // Check elaborated bounds.
2313        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2314
2315        for (pred, obligation_span) in implied_obligations {
2316            match pred.kind().skip_binder() {
2317                // We lower empty bounds like `Vec<dyn Copy>:` as
2318                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2319                // regular WF checking
2320                ty::ClauseKind::WellFormed(..)
2321                // Unstable feature goals cannot be proven in an empty environment so skip them
2322                | ty::ClauseKind::UnstableFeature(..) => continue,
2323                _ => {}
2324            }
2325
2326            // Match the existing behavior.
2327            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2328                let pred = self.normalize(span, None, pred);
2329
2330                // only use the span of the predicate clause (#90869)
2331                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2332                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2333                    span = predicates
2334                        .iter()
2335                        // There seems to be no better way to find out which predicate we are in
2336                        .find(|pred| pred.span.contains(obligation_span))
2337                        .map(|pred| pred.span)
2338                        .unwrap_or(obligation_span);
2339                }
2340
2341                let obligation = Obligation::new(
2342                    tcx,
2343                    traits::ObligationCause::new(
2344                        span,
2345                        self.body_def_id,
2346                        ObligationCauseCode::TrivialBound,
2347                    ),
2348                    empty_env,
2349                    pred,
2350                );
2351                self.ocx.register_obligation(obligation);
2352            }
2353        }
2354    }
2355}
2356
2357pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2358    let items = tcx.hir_crate_items(());
2359    let res =
2360        items
2361            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2362            .and(
2363                items.par_impl_items(|item| {
2364                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2365                }),
2366            )
2367            .and(items.par_trait_items(|item| {
2368                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2369            }))
2370            .and(items.par_foreign_items(|item| {
2371                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2372            }))
2373            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2374            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2375    super::entry::check_for_entry_fn(tcx);
2376
2377    res
2378}
2379
2380fn lint_redundant_lifetimes<'tcx>(
2381    tcx: TyCtxt<'tcx>,
2382    owner_id: LocalDefId,
2383    outlives_env: &OutlivesEnvironment<'tcx>,
2384) {
2385    let def_kind = tcx.def_kind(owner_id);
2386    match def_kind {
2387        DefKind::Struct
2388        | DefKind::Union
2389        | DefKind::Enum
2390        | DefKind::Trait
2391        | DefKind::TraitAlias
2392        | DefKind::Fn
2393        | DefKind::Const { .. }
2394        | DefKind::Impl { of_trait: _ } => {
2395            // Proceed
2396        }
2397        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2398            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2399                // Don't check for redundant lifetimes for associated items of trait
2400                // implementations, since the signature is required to be compatible
2401                // with the trait, even if the implementation implies some lifetimes
2402                // are redundant.
2403                return;
2404            }
2405        }
2406        DefKind::Mod
2407        | DefKind::Variant
2408        | DefKind::TyAlias
2409        | DefKind::ForeignTy
2410        | DefKind::TyParam
2411        | DefKind::ConstParam
2412        | DefKind::Static { .. }
2413        | DefKind::Ctor(_, _)
2414        | DefKind::Macro(_)
2415        | DefKind::ExternCrate
2416        | DefKind::Use
2417        | DefKind::ForeignMod
2418        | DefKind::AnonConst
2419        | DefKind::InlineConst
2420        | DefKind::OpaqueTy
2421        | DefKind::Field
2422        | DefKind::LifetimeParam
2423        | DefKind::GlobalAsm
2424        | DefKind::Closure
2425        | DefKind::SyntheticCoroutineBody => return,
2426    }
2427
2428    // The ordering of this lifetime map is a bit subtle.
2429    //
2430    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2431    // where we can prove that `'candidate = 'victim`.
2432    //
2433    // `'static` must come first in this list because we can never replace `'static` with
2434    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2435    // suggest replacing `'a` with `'static`.
2436    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];
2437    lifetimes.extend(
2438        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2439    );
2440    // If we are in a function, add its late-bound lifetimes too.
2441    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2442        for (idx, var) in
2443            tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2444        {
2445            let ty::BoundVariableKind::Region(kind) = var else { continue };
2446            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2447            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2448        }
2449    }
2450    lifetimes.retain(|candidate| candidate.is_named(tcx));
2451
2452    // Keep track of lifetimes which have already been replaced with other lifetimes.
2453    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2454    // both `'a` and `'b`.
2455    let mut shadowed = FxHashSet::default();
2456
2457    for (idx, &candidate) in lifetimes.iter().enumerate() {
2458        // Don't suggest removing a lifetime twice. We only need to check this
2459        // here and not up in the `victim` loop because equality is transitive,
2460        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2461        // A's victim loop.
2462        if shadowed.contains(&candidate) {
2463            continue;
2464        }
2465
2466        for &victim in &lifetimes[(idx + 1)..] {
2467            // All region parameters should have a `DefId` available as:
2468            // - Late-bound parameters should be of the`BrNamed` variety,
2469            // since we get these signatures straight from `hir_lowering`.
2470            // - Early-bound parameters unconditionally have a `DefId` available.
2471            //
2472            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2473            // can't really suggest to remove them.
2474            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2475                continue;
2476            };
2477
2478            // Do not rename lifetimes not local to this item since they'll overlap
2479            // with the lint running on the parent. We still want to consider parent
2480            // lifetimes which make child lifetimes redundant, otherwise we would
2481            // have truncated the `identity_for_item` args above.
2482            if tcx.parent(def_id) != owner_id.to_def_id() {
2483                continue;
2484            }
2485
2486            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2487            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2488                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2489            {
2490                shadowed.insert(victim);
2491                tcx.emit_node_span_lint(
2492                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2493                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2494                    tcx.def_span(def_id),
2495                    RedundantLifetimeArgsLint { candidate, victim },
2496                );
2497            }
2498        }
2499    }
2500}
2501
2502#[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)]
2503#[diag("unnecessary lifetime parameter `{$victim}`")]
2504#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2505struct RedundantLifetimeArgsLint<'tcx> {
2506    /// The lifetime we have found to be redundant.
2507    victim: ty::Region<'tcx>,
2508    // The lifetime we can replace the victim with.
2509    candidate: ty::Region<'tcx>,
2510}