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