Skip to main content

rustc_hir_analysis/check/
wfcheck.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let loc = Some(WellFormedLoc::Ty(def_id));
            enter_wf_checking_ctxt(tcx, def_id,
                |wfcx|
                    {
                        let item = tcx.associated_item(def_id);
                        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
                        let self_ty =
                            match item.container {
                                ty::AssocContainer::Trait => tcx.types.self_param,
                                ty::AssocContainer::InherentImpl |
                                    ty::AssocContainer::TraitImpl(_) => {
                                    tcx.type_of(item.container_id(tcx)).instantiate_identity()
                                }
                            };
                        let span = tcx.def_span(def_id);
                        match item.kind {
                            ty::AssocKind::Const { .. } => {
                                let ty = tcx.type_of(def_id).instantiate_identity();
                                let ty =
                                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                        ty);
                                wfcx.register_wf_obligation(span, loc, ty.into());
                                let has_value = item.defaultness(tcx).has_value();
                                if tcx.is_type_const(def_id) {
                                    check_type_const(wfcx, def_id, ty, has_value)?;
                                }
                                if has_value {
                                    let code = ObligationCauseCode::SizedConstOrStatic;
                                    wfcx.register_bound(ObligationCause::new(span, def_id,
                                            code), wfcx.param_env, ty,
                                        tcx.require_lang_item(LangItem::Sized, span));
                                }
                                Ok(())
                            }
                            ty::AssocKind::Fn { .. } => {
                                let sig = tcx.fn_sig(def_id).instantiate_identity();
                                let hir_sig =
                                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
                                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
                                check_method_receiver(wfcx, hir_sig, item, self_ty)
                            }
                            ty::AssocKind::Type { .. } => {
                                if let ty::AssocContainer::Trait = item.container {
                                    check_associated_type_bounds(wfcx, item, span)
                                }
                                if item.defaultness(tcx).has_value() {
                                    let ty = tcx.type_of(def_id).instantiate_identity();
                                    let ty =
                                        wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                            ty);
                                    wfcx.register_wf_obligation(span, loc, ty.into());
                                }
                                Ok(())
                            }
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
953pub(crate) fn check_associated_item(
954    tcx: TyCtxt<'_>,
955    def_id: LocalDefId,
956) -> Result<(), ErrorGuaranteed> {
957    let loc = Some(WellFormedLoc::Ty(def_id));
958    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
959        let item = tcx.associated_item(def_id);
960
961        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
962        // other `Foo` impls are incoherent.
963        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
964
965        let self_ty = match item.container {
966            ty::AssocContainer::Trait => tcx.types.self_param,
967            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
968                tcx.type_of(item.container_id(tcx)).instantiate_identity()
969            }
970        };
971
972        let span = tcx.def_span(def_id);
973
974        match item.kind {
975            ty::AssocKind::Const { .. } => {
976                let ty = tcx.type_of(def_id).instantiate_identity();
977                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
978                wfcx.register_wf_obligation(span, loc, ty.into());
979
980                let has_value = item.defaultness(tcx).has_value();
981                if tcx.is_type_const(def_id) {
982                    check_type_const(wfcx, def_id, ty, has_value)?;
983                }
984
985                if has_value {
986                    let code = ObligationCauseCode::SizedConstOrStatic;
987                    wfcx.register_bound(
988                        ObligationCause::new(span, def_id, code),
989                        wfcx.param_env,
990                        ty,
991                        tcx.require_lang_item(LangItem::Sized, span),
992                    );
993                }
994
995                Ok(())
996            }
997            ty::AssocKind::Fn { .. } => {
998                let sig = tcx.fn_sig(def_id).instantiate_identity();
999                let hir_sig =
1000                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1001                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1002                check_method_receiver(wfcx, hir_sig, item, self_ty)
1003            }
1004            ty::AssocKind::Type { .. } => {
1005                if let ty::AssocContainer::Trait = item.container {
1006                    check_associated_type_bounds(wfcx, item, span)
1007                }
1008                if item.defaultness(tcx).has_value() {
1009                    let ty = tcx.type_of(def_id).instantiate_identity();
1010                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1011                    wfcx.register_wf_obligation(span, loc, ty.into());
1012                }
1013                Ok(())
1014            }
1015        }
1016    })
1017}
1018
1019/// In a type definition, we check that to ensure that the types of the fields are well-formed.
1020fn check_type_defn<'tcx>(
1021    tcx: TyCtxt<'tcx>,
1022    item: &hir::Item<'tcx>,
1023    all_sized: bool,
1024) -> Result<(), ErrorGuaranteed> {
1025    tcx.ensure_ok().check_representability(item.owner_id.def_id);
1026    let adt_def = tcx.adt_def(item.owner_id);
1027
1028    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1029        let variants = adt_def.variants();
1030        let packed = adt_def.repr().packed();
1031
1032        for variant in variants.iter() {
1033            // All field types must be well-formed.
1034            for field in &variant.fields {
1035                if let Some(def_id) = field.value
1036                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1037                {
1038                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1039                    // be refactored to check the instantiate-ability of the code better.
1040                    if let Some(def_id) = def_id.as_local()
1041                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1042                        && let expr = &tcx.hir_body(anon.body).value
1043                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1044                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1045                    {
1046                        // Do not evaluate bare `const` params, as those would ICE and are only
1047                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1048                    } else {
1049                        // Evaluate the constant proactively, to emit an error if the constant has
1050                        // an unconditional error. We only do so if the const has no type params.
1051                        let _ = tcx.const_eval_poly(def_id);
1052                    }
1053                }
1054                let field_id = field.did.expect_local();
1055                let hir::FieldDef { ty: hir_ty, .. } =
1056                    tcx.hir_node_by_def_id(field_id).expect_field();
1057                let ty = wfcx.deeply_normalize(
1058                    hir_ty.span,
1059                    None,
1060                    tcx.type_of(field.did).instantiate_identity(),
1061                );
1062                wfcx.register_wf_obligation(
1063                    hir_ty.span,
1064                    Some(WellFormedLoc::Ty(field_id)),
1065                    ty.into(),
1066                );
1067
1068                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())
1069                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1070                {
1071                    // Scalable vectors can only be fields of structs if the type has a
1072                    // `rustc_scalable_vector` attribute w/out specifying an element count
1073                    tcx.dcx().span_err(
1074                        hir_ty.span,
1075                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1076                            "scalable vectors cannot be fields of a {}",
1077                            adt_def.variant_descr()
1078                        ),
1079                    );
1080                }
1081            }
1082
1083            // For DST, or when drop needs to copy things around, all
1084            // intermediate types must be sized.
1085            let needs_drop_copy = || {
1086                packed && {
1087                    let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1088                    let ty = tcx.erase_and_anonymize_regions(ty);
1089                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1090                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1091                }
1092            };
1093            // All fields (except for possibly the last) should be sized.
1094            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1095            let unsized_len = if all_sized { 0 } else { 1 };
1096            for (idx, field) in
1097                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1098            {
1099                let last = idx == variant.fields.len() - 1;
1100                let field_id = field.did.expect_local();
1101                let hir::FieldDef { ty: hir_ty, .. } =
1102                    tcx.hir_node_by_def_id(field_id).expect_field();
1103                let ty = wfcx.normalize(
1104                    hir_ty.span,
1105                    None,
1106                    tcx.type_of(field.did).instantiate_identity(),
1107                );
1108                wfcx.register_bound(
1109                    traits::ObligationCause::new(
1110                        hir_ty.span,
1111                        wfcx.body_def_id,
1112                        ObligationCauseCode::FieldSized {
1113                            adt_kind: match &item.kind {
1114                                ItemKind::Struct(..) => AdtKind::Struct,
1115                                ItemKind::Union(..) => AdtKind::Union,
1116                                ItemKind::Enum(..) => AdtKind::Enum,
1117                                kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
    format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1118                                    item.span,
1119                                    "should be wfchecking an ADT, got {kind:?}"
1120                                ),
1121                            },
1122                            span: hir_ty.span,
1123                            last,
1124                        },
1125                    ),
1126                    wfcx.param_env,
1127                    ty,
1128                    tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1129                );
1130            }
1131
1132            // Explicit `enum` discriminant values must const-evaluate successfully.
1133            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1134                match tcx.const_eval_poly(discr_def_id) {
1135                    Ok(_) => {}
1136                    Err(ErrorHandled::Reported(..)) => {}
1137                    Err(ErrorHandled::TooGeneric(sp)) => {
1138                        ::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")
1139                    }
1140                }
1141            }
1142        }
1143
1144        check_where_clauses(wfcx, item.owner_id.def_id);
1145        Ok(())
1146    })
1147}
1148
1149#[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(1149u32),
                                    ::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:1151",
                                    "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(1151u32),
                                    ::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))]
1150fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1151    debug!(?item.owner_id);
1152
1153    let def_id = item.owner_id.def_id;
1154    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1155        // `PointeeSized` is removed during lowering.
1156        return Ok(());
1157    }
1158
1159    let trait_def = tcx.trait_def(def_id);
1160    if trait_def.is_marker
1161        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1162    {
1163        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1164            struct_span_code_err!(
1165                tcx.dcx(),
1166                tcx.def_span(*associated_def_id),
1167                E0714,
1168                "marker traits cannot have associated items",
1169            )
1170            .emit();
1171        }
1172    }
1173
1174    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1175        check_where_clauses(wfcx, def_id);
1176        Ok(())
1177    });
1178
1179    // Only check traits, don't check trait aliases
1180    if let hir::ItemKind::Trait(..) = item.kind {
1181        check_gat_where_clauses(tcx, item.owner_id.def_id);
1182    }
1183    res
1184}
1185
1186/// Checks all associated type defaults of trait `trait_def_id`.
1187///
1188/// Assuming the defaults are used, check that all predicates (bounds on the
1189/// assoc type and where clauses on the trait) hold.
1190fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1191    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1192
1193    {
    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:1193",
                        "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(1193u32),
                        ::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);
1194    let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1195        traits::wf::clause_obligations(
1196            wfcx.infcx,
1197            wfcx.param_env,
1198            wfcx.body_def_id,
1199            bound,
1200            bound_span,
1201        )
1202    });
1203
1204    wfcx.register_obligations(wf_obligations);
1205}
1206
1207fn check_item_fn(
1208    tcx: TyCtxt<'_>,
1209    def_id: LocalDefId,
1210    decl: &hir::FnDecl<'_>,
1211) -> Result<(), ErrorGuaranteed> {
1212    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1213        check_eiis_fn(tcx, def_id);
1214
1215        let sig = tcx.fn_sig(def_id).instantiate_identity();
1216        check_fn_or_method(wfcx, sig, decl, def_id);
1217        Ok(())
1218    })
1219}
1220
1221fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1222    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1223    // that was used to mark the implementation. This is a two step process.
1224    for EiiImpl { resolution, span, .. } in
1225        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                        break 'done Some(impls);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1226    {
1227        let (foreign_item, name) = match resolution {
1228            EiiImplResolution::Macro(def_id) => {
1229                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1230                // signature that we'd like to compare the function we're currently checking with
1231                if let Some(foreign_item) =
1232                    {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1233                {
1234                    (foreign_item, tcx.item_name(*def_id))
1235                } else {
1236                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1237                    continue;
1238                }
1239            }
1240            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1241            EiiImplResolution::Error(_eg) => continue,
1242        };
1243
1244        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1245    }
1246}
1247
1248fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1249    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1250    // that was used to mark the implementation. This is a two step process.
1251    for EiiImpl { resolution, span, .. } in
1252        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                        break 'done Some(impls);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1253    {
1254        let (foreign_item, name) = match resolution {
1255            EiiImplResolution::Macro(def_id) => {
1256                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1257                // signature that we'd like to compare the function we're currently checking with
1258                if let Some(foreign_item) =
1259                    {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1260                {
1261                    (foreign_item, tcx.item_name(*def_id))
1262                } else {
1263                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1264                    continue;
1265                }
1266            }
1267            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1268            EiiImplResolution::Error(_eg) => continue,
1269        };
1270
1271        let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1272    }
1273}
1274
1275#[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(1275u32),
                                    ::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|
                    {
                        if should_check_for_sync {
                            check_eiis_static(tcx, item_id, ty);
                        }
                        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))]
1276pub(crate) fn check_static_item<'tcx>(
1277    tcx: TyCtxt<'tcx>,
1278    item_id: LocalDefId,
1279    ty: Ty<'tcx>,
1280    should_check_for_sync: bool,
1281) -> Result<(), ErrorGuaranteed> {
1282    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1283        if should_check_for_sync {
1284            check_eiis_static(tcx, item_id, ty);
1285        }
1286
1287        let span = tcx.ty_span(item_id);
1288        let loc = Some(WellFormedLoc::Ty(item_id));
1289        let item_ty = wfcx.deeply_normalize(span, loc, ty);
1290
1291        let is_foreign_item = tcx.is_foreign_item(item_id);
1292        let is_structurally_foreign_item = || {
1293            let tail = tcx.struct_tail_raw(
1294                item_ty,
1295                &ObligationCause::dummy(),
1296                |ty| wfcx.deeply_normalize(span, loc, ty),
1297                || {},
1298            );
1299
1300            matches!(tail.kind(), ty::Foreign(_))
1301        };
1302        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1303
1304        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1305        if forbid_unsized {
1306            let span = tcx.def_span(item_id);
1307            wfcx.register_bound(
1308                traits::ObligationCause::new(
1309                    span,
1310                    wfcx.body_def_id,
1311                    ObligationCauseCode::SizedConstOrStatic,
1312                ),
1313                wfcx.param_env,
1314                item_ty,
1315                tcx.require_lang_item(LangItem::Sized, span),
1316            );
1317        }
1318
1319        // Ensure that the end result is `Sync` in a non-thread local `static`.
1320        let should_check_for_sync = should_check_for_sync
1321            && !is_foreign_item
1322            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1323            && !tcx.is_thread_local_static(item_id.to_def_id());
1324
1325        if should_check_for_sync {
1326            wfcx.register_bound(
1327                traits::ObligationCause::new(
1328                    span,
1329                    wfcx.body_def_id,
1330                    ObligationCauseCode::SharedStatic,
1331                ),
1332                wfcx.param_env,
1333                item_ty,
1334                tcx.require_lang_item(LangItem::Sync, span),
1335            );
1336        }
1337        Ok(())
1338    })
1339}
1340
1341#[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(1341u32),
                                    ::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))]
1342pub(super) fn check_type_const<'tcx>(
1343    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1344    def_id: LocalDefId,
1345    item_ty: Ty<'tcx>,
1346    has_value: bool,
1347) -> Result<(), ErrorGuaranteed> {
1348    let tcx = wfcx.tcx();
1349    let span = tcx.def_span(def_id);
1350
1351    wfcx.register_bound(
1352        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1353        wfcx.param_env,
1354        item_ty,
1355        tcx.require_lang_item(LangItem::ConstParamTy, span),
1356    );
1357
1358    if has_value {
1359        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1360        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1361        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1362
1363        wfcx.register_obligation(Obligation::new(
1364            tcx,
1365            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1366            wfcx.param_env,
1367            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1368        ));
1369    }
1370    Ok(())
1371}
1372
1373#[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(1373u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            enter_wf_checking_ctxt(tcx, item.owner_id.def_id,
                |wfcx|
                    {
                        match impl_.of_trait {
                            Some(of_trait) => {
                                let trait_ref =
                                    tcx.impl_trait_ref(item.owner_id).instantiate_identity();
                                tcx.ensure_result().coherent_trait(trait_ref.def_id)?;
                                let trait_span = of_trait.trait_ref.path.span;
                                let trait_ref =
                                    wfcx.deeply_normalize(trait_span,
                                        Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                        trait_ref);
                                let trait_pred =
                                    ty::TraitPredicate {
                                        trait_ref,
                                        polarity: ty::PredicatePolarity::Positive,
                                    };
                                let mut obligations =
                                    traits::wf::trait_obligations(wfcx.infcx, wfcx.param_env,
                                        wfcx.body_def_id, trait_pred, trait_span, item);
                                for obligation in &mut obligations {
                                    if obligation.cause.span != trait_span { continue; }
                                    if let Some(pred) = obligation.predicate.as_trait_clause()
                                            && pred.skip_binder().self_ty() == trait_ref.self_ty() {
                                        obligation.cause.span = impl_.self_ty.span;
                                    }
                                    if let Some(pred) =
                                                obligation.predicate.as_projection_clause() &&
                                            pred.skip_binder().self_ty() == trait_ref.self_ty() {
                                        obligation.cause.span = impl_.self_ty.span;
                                    }
                                }
                                if tcx.is_conditionally_const(item.owner_id.def_id) {
                                    for (bound, _) in
                                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx,
                                            trait_ref.args) {
                                        let bound =
                                            wfcx.normalize(item.span,
                                                Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                                bound);
                                        wfcx.register_obligation(Obligation::new(tcx,
                                                ObligationCause::new(impl_.self_ty.span, wfcx.body_def_id,
                                                    ObligationCauseCode::WellFormed(None)), wfcx.param_env,
                                                bound.to_host_effect_clause(tcx,
                                                    ty::BoundConstness::Maybe)))
                                    }
                                }
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1445",
                                                        "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(1445u32),
                                                        ::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_))]
1374fn check_impl<'tcx>(
1375    tcx: TyCtxt<'tcx>,
1376    item: &'tcx hir::Item<'tcx>,
1377    impl_: &hir::Impl<'_>,
1378) -> Result<(), ErrorGuaranteed> {
1379    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1380        match impl_.of_trait {
1381            Some(of_trait) => {
1382                // `#[rustc_reservation_impl]` impls are not real impls and
1383                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1384                // won't hold).
1385                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1386                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1387                // case other `Foo` impls are incoherent.
1388                tcx.ensure_result().coherent_trait(trait_ref.def_id)?;
1389                let trait_span = of_trait.trait_ref.path.span;
1390                let trait_ref = wfcx.deeply_normalize(
1391                    trait_span,
1392                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1393                    trait_ref,
1394                );
1395                let trait_pred =
1396                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1397                let mut obligations = traits::wf::trait_obligations(
1398                    wfcx.infcx,
1399                    wfcx.param_env,
1400                    wfcx.body_def_id,
1401                    trait_pred,
1402                    trait_span,
1403                    item,
1404                );
1405                for obligation in &mut obligations {
1406                    if obligation.cause.span != trait_span {
1407                        // We already have a better span.
1408                        continue;
1409                    }
1410                    if let Some(pred) = obligation.predicate.as_trait_clause()
1411                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1412                    {
1413                        obligation.cause.span = impl_.self_ty.span;
1414                    }
1415                    if let Some(pred) = obligation.predicate.as_projection_clause()
1416                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1417                    {
1418                        obligation.cause.span = impl_.self_ty.span;
1419                    }
1420                }
1421
1422                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1423                if tcx.is_conditionally_const(item.owner_id.def_id) {
1424                    for (bound, _) in
1425                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1426                    {
1427                        let bound = wfcx.normalize(
1428                            item.span,
1429                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1430                            bound,
1431                        );
1432                        wfcx.register_obligation(Obligation::new(
1433                            tcx,
1434                            ObligationCause::new(
1435                                impl_.self_ty.span,
1436                                wfcx.body_def_id,
1437                                ObligationCauseCode::WellFormed(None),
1438                            ),
1439                            wfcx.param_env,
1440                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1441                        ))
1442                    }
1443                }
1444
1445                debug!(?obligations);
1446                wfcx.register_obligations(obligations);
1447            }
1448            None => {
1449                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1450                let self_ty = wfcx.deeply_normalize(
1451                    item.span,
1452                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1453                    self_ty,
1454                );
1455                wfcx.register_wf_obligation(
1456                    impl_.self_ty.span,
1457                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1458                    self_ty.into(),
1459                );
1460            }
1461        }
1462
1463        check_where_clauses(wfcx, item.owner_id.def_id);
1464        Ok(())
1465    })
1466}
1467
1468/// Checks where-clauses and inline bounds that are declared on `def_id`.
1469#[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(1469u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = wfcx.infcx;
            let tcx = wfcx.tcx();
            let predicates = tcx.predicates_of(def_id.to_def_id());
            let generics = tcx.generics_of(def_id);
            for param in &generics.own_params {
                if let Some(default) =
                        param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
                    {
                    if !default.has_param() {
                        wfcx.register_wf_obligation(tcx.def_span(param.def_id),
                            (#[allow(non_exhaustive_omitted_patterns)] match param.kind
                                    {
                                    GenericParamDefKind::Type { .. } => true,
                                    _ => false,
                                }).then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
                            default.as_term().unwrap());
                    } else {
                        let GenericArgKind::Const(ct) =
                            default.kind() else { continue; };
                        let ct_ty =
                            match ct.kind() {
                                ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
                                    ty::ConstKind::Bound(_, _) =>
                                    ::core::panicking::panic("internal error: entered unreachable code"),
                                ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
                                    continue,
                                ty::ConstKind::Value(cv) => cv.ty,
                                ty::ConstKind::Unevaluated(uv) => {
                                    infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
                                }
                                ty::ConstKind::Param(param_ct) => {
                                    param_ct.find_const_ty_from_env(wfcx.param_env)
                                }
                            };
                        let param_ty =
                            tcx.type_of(param.def_id).instantiate_identity();
                        if !ct_ty.has_param() && !param_ty.has_param() {
                            let cause =
                                traits::ObligationCause::new(tcx.def_span(param.def_id),
                                    wfcx.body_def_id, ObligationCauseCode::WellFormed(None));
                            wfcx.register_obligation(Obligation::new(tcx, cause,
                                    wfcx.param_env,
                                    ty::ClauseKind::ConstArgHasType(ct, param_ty)));
                        }
                    }
                }
            }
            let args =
                GenericArgs::for_item(tcx, def_id.to_def_id(),
                    |param, _|
                        {
                            if param.index >= generics.parent_count as u32 &&
                                        let Some(default) =
                                            param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
                                    && !default.has_param() {
                                return default;
                            }
                            tcx.mk_param_from_def(param)
                        });
            let default_obligations =
                predicates.predicates.iter().flat_map(|&(pred, sp)|
                            {
                                struct CountParams {
                                    params: FxHashSet<u32>,
                                }
                                #[automatically_derived]
                                impl ::core::default::Default for CountParams {
                                    #[inline]
                                    fn default() -> CountParams {
                                        CountParams { params: ::core::default::Default::default() }
                                    }
                                }
                                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
                                    type Result = ControlFlow<()>;
                                    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
                                        if let ty::Param(param) = t.kind() {
                                            self.params.insert(param.index);
                                        }
                                        t.super_visit_with(self)
                                    }
                                    fn visit_region(&mut self, _: ty::Region<'tcx>)
                                        -> Self::Result {
                                        ControlFlow::Break(())
                                    }
                                    fn visit_const(&mut self, c: ty::Const<'tcx>)
                                        -> Self::Result {
                                        if let ty::ConstKind::Param(param) = c.kind() {
                                            self.params.insert(param.index);
                                        }
                                        c.super_visit_with(self)
                                    }
                                }
                                let mut param_count = CountParams::default();
                                let has_region =
                                    pred.visit_with(&mut param_count).is_break();
                                let instantiated_pred =
                                    ty::EarlyBinder::bind(pred).instantiate(tcx, args);
                                if instantiated_pred.has_non_region_param() ||
                                            param_count.params.len() > 1 || has_region {
                                    None
                                } else if predicates.predicates.iter().any(|&(p, _)|
                                            p == instantiated_pred) {
                                    None
                                } else { Some((instantiated_pred, sp)) }
                            }).map(|(pred, sp)|
                        {
                            let pred = wfcx.normalize(sp, None, pred);
                            let cause =
                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                            Obligation::new(tcx, cause, wfcx.param_env, pred)
                        });
            let predicates = predicates.instantiate_identity(tcx);
            let assoc_const_obligations: Vec<_> =
                predicates.predicates.iter().copied().zip(predicates.spans.iter().copied()).filter_map(|(clause,
                                sp)|
                            {
                                let proj = clause.as_projection_clause()?;
                                let pred_binder =
                                    proj.map_bound(|pred|
                                                {
                                                    pred.term.as_const().map(|ct|
                                                            {
                                                                let assoc_const_ty =
                                                                    tcx.type_of(pred.projection_term.def_id).instantiate(tcx,
                                                                        pred.projection_term.args);
                                                                ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
                                                            })
                                                }).transpose();
                                pred_binder.map(|pred_binder|
                                        {
                                            let cause =
                                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                                            Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
                                        })
                            }).collect();
            match (&predicates.predicates.len(), &predicates.spans.len()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let wf_obligations =
                predicates.into_iter().flat_map(|(p, sp)|
                        {
                            traits::wf::clause_obligations(infcx, wfcx.param_env,
                                wfcx.body_def_id, p, sp)
                        });
            let obligations: Vec<_> =
                wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
            wfcx.register_obligations(obligations);
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1470pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1471    let infcx = wfcx.infcx;
1472    let tcx = wfcx.tcx();
1473
1474    let predicates = tcx.predicates_of(def_id.to_def_id());
1475    let generics = tcx.generics_of(def_id);
1476
1477    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1478    // For example, this forbids the declaration:
1479    //
1480    //     struct Foo<T = Vec<[u32]>> { .. }
1481    //
1482    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1483    for param in &generics.own_params {
1484        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1485            // Ignore dependent defaults -- that is, where the default of one type
1486            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1487            // be sure if it will error or not as user might always specify the other.
1488            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1489            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1490            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1491            if !default.has_param() {
1492                wfcx.register_wf_obligation(
1493                    tcx.def_span(param.def_id),
1494                    matches!(param.kind, GenericParamDefKind::Type { .. })
1495                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1496                    default.as_term().unwrap(),
1497                );
1498            } else {
1499                // If we've got a generic const parameter we still want to check its
1500                // type is correct in case both it and the param type are fully concrete.
1501                let GenericArgKind::Const(ct) = default.kind() else {
1502                    continue;
1503                };
1504
1505                let ct_ty = match ct.kind() {
1506                    ty::ConstKind::Infer(_)
1507                    | ty::ConstKind::Placeholder(_)
1508                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1509                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1510                    ty::ConstKind::Value(cv) => cv.ty,
1511                    ty::ConstKind::Unevaluated(uv) => {
1512                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1513                    }
1514                    ty::ConstKind::Param(param_ct) => {
1515                        param_ct.find_const_ty_from_env(wfcx.param_env)
1516                    }
1517                };
1518
1519                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1520                if !ct_ty.has_param() && !param_ty.has_param() {
1521                    let cause = traits::ObligationCause::new(
1522                        tcx.def_span(param.def_id),
1523                        wfcx.body_def_id,
1524                        ObligationCauseCode::WellFormed(None),
1525                    );
1526                    wfcx.register_obligation(Obligation::new(
1527                        tcx,
1528                        cause,
1529                        wfcx.param_env,
1530                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1531                    ));
1532                }
1533            }
1534        }
1535    }
1536
1537    // Check that trait predicates are WF when params are instantiated with their defaults.
1538    // We don't want to overly constrain the predicates that may be written but we want to
1539    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1540    // Therefore we check if a predicate which contains a single type param
1541    // with a concrete default is WF with that default instantiated.
1542    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1543    //
1544    // First we build the defaulted generic parameters.
1545    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1546        if param.index >= generics.parent_count as u32
1547            // If the param has a default, ...
1548            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1549            // ... and it's not a dependent default, ...
1550            && !default.has_param()
1551        {
1552            // ... then instantiate it with the default.
1553            return default;
1554        }
1555        tcx.mk_param_from_def(param)
1556    });
1557
1558    // Now we build the instantiated predicates.
1559    let default_obligations = predicates
1560        .predicates
1561        .iter()
1562        .flat_map(|&(pred, sp)| {
1563            #[derive(Default)]
1564            struct CountParams {
1565                params: FxHashSet<u32>,
1566            }
1567            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1568                type Result = ControlFlow<()>;
1569                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1570                    if let ty::Param(param) = t.kind() {
1571                        self.params.insert(param.index);
1572                    }
1573                    t.super_visit_with(self)
1574                }
1575
1576                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1577                    ControlFlow::Break(())
1578                }
1579
1580                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1581                    if let ty::ConstKind::Param(param) = c.kind() {
1582                        self.params.insert(param.index);
1583                    }
1584                    c.super_visit_with(self)
1585                }
1586            }
1587            let mut param_count = CountParams::default();
1588            let has_region = pred.visit_with(&mut param_count).is_break();
1589            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1590            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1591            // or preds with multiple params.
1592            if instantiated_pred.has_non_region_param()
1593                || param_count.params.len() > 1
1594                || has_region
1595            {
1596                None
1597            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1598                // Avoid duplication of predicates that contain no parameters, for example.
1599                None
1600            } else {
1601                Some((instantiated_pred, sp))
1602            }
1603        })
1604        .map(|(pred, sp)| {
1605            // Convert each of those into an obligation. So if you have
1606            // something like `struct Foo<T: Copy = String>`, we would
1607            // take that predicate `T: Copy`, instantiated with `String: Copy`
1608            // (actually that happens in the previous `flat_map` call),
1609            // and then try to prove it (in this case, we'll fail).
1610            //
1611            // Note the subtle difference from how we handle `predicates`
1612            // below: there, we are not trying to prove those predicates
1613            // to be *true* but merely *well-formed*.
1614            let pred = wfcx.normalize(sp, None, pred);
1615            let cause = traits::ObligationCause::new(
1616                sp,
1617                wfcx.body_def_id,
1618                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1619            );
1620            Obligation::new(tcx, cause, wfcx.param_env, pred)
1621        });
1622
1623    let predicates = predicates.instantiate_identity(tcx);
1624
1625    let assoc_const_obligations: Vec<_> = predicates
1626        .predicates
1627        .iter()
1628        .copied()
1629        .zip(predicates.spans.iter().copied())
1630        .filter_map(|(clause, sp)| {
1631            let proj = clause.as_projection_clause()?;
1632            let pred_binder = proj
1633                .map_bound(|pred| {
1634                    pred.term.as_const().map(|ct| {
1635                        let assoc_const_ty = tcx
1636                            .type_of(pred.projection_term.def_id)
1637                            .instantiate(tcx, pred.projection_term.args);
1638                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1639                    })
1640                })
1641                .transpose();
1642            pred_binder.map(|pred_binder| {
1643                let cause = traits::ObligationCause::new(
1644                    sp,
1645                    wfcx.body_def_id,
1646                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1647                );
1648                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1649            })
1650        })
1651        .collect();
1652
1653    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1654    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1655        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1656    });
1657    let obligations: Vec<_> =
1658        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1659    wfcx.register_obligations(obligations);
1660}
1661
1662#[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(1662u32),
                                    ::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))]
1663fn check_fn_or_method<'tcx>(
1664    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1665    sig: ty::PolyFnSig<'tcx>,
1666    hir_decl: &hir::FnDecl<'_>,
1667    def_id: LocalDefId,
1668) {
1669    let tcx = wfcx.tcx();
1670    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1671
1672    // Normalize the input and output types one at a time, using a different
1673    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1674    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1675    // for each type, preventing the HIR wf check from generating
1676    // a nice error message.
1677    let arg_span =
1678        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1679
1680    sig.inputs_and_output =
1681        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1682            wfcx.deeply_normalize(
1683                arg_span(idx),
1684                Some(WellFormedLoc::Param {
1685                    function: def_id,
1686                    // Note that the `param_idx` of the output type is
1687                    // one greater than the index of the last input type.
1688                    param_idx: idx,
1689                }),
1690                ty,
1691            )
1692        }));
1693
1694    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1695        wfcx.register_wf_obligation(
1696            arg_span(idx),
1697            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1698            ty.into(),
1699        );
1700    }
1701
1702    check_where_clauses(wfcx, def_id);
1703
1704    if sig.abi == ExternAbi::RustCall {
1705        let span = tcx.def_span(def_id);
1706        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1707        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1708        // Check that the argument is a tuple and is sized
1709        if let Some(ty) = inputs.next() {
1710            wfcx.register_bound(
1711                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1712                wfcx.param_env,
1713                *ty,
1714                tcx.require_lang_item(hir::LangItem::Tuple, span),
1715            );
1716            wfcx.register_bound(
1717                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1718                wfcx.param_env,
1719                *ty,
1720                tcx.require_lang_item(hir::LangItem::Sized, span),
1721            );
1722        } else {
1723            tcx.dcx().span_err(
1724                hir_decl.inputs.last().map_or(span, |input| input.span),
1725                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1726            );
1727        }
1728        // No more inputs other than the `self` type and the tuple type
1729        if inputs.next().is_some() {
1730            tcx.dcx().span_err(
1731                hir_decl.inputs.last().map_or(span, |input| input.span),
1732                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1733            );
1734        }
1735    }
1736
1737    // If the function has a body, additionally require that the return type is sized.
1738    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1739        let span = match hir_decl.output {
1740            hir::FnRetTy::Return(ty) => ty.span,
1741            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1742        };
1743
1744        wfcx.register_bound(
1745            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1746            wfcx.param_env,
1747            sig.output(),
1748            tcx.require_lang_item(LangItem::Sized, span),
1749        );
1750    }
1751}
1752
1753/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1754#[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)]
1755enum ArbitrarySelfTypesLevel {
1756    Basic,        // just arbitrary_self_types
1757    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1758}
1759
1760#[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(1760u32),
                                    ::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:1780",
                                    "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(1780u32),
                                    ::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))]
1761fn check_method_receiver<'tcx>(
1762    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1763    fn_sig: &hir::FnSig<'_>,
1764    method: ty::AssocItem,
1765    self_ty: Ty<'tcx>,
1766) -> Result<(), ErrorGuaranteed> {
1767    let tcx = wfcx.tcx();
1768
1769    if !method.is_method() {
1770        return Ok(());
1771    }
1772
1773    let span = fn_sig.decl.inputs[0].span;
1774    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1775
1776    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1777    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1778    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1779
1780    debug!("check_method_receiver: sig={:?}", sig);
1781
1782    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1783
1784    let receiver_ty = sig.inputs()[0];
1785    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1786
1787    // If the receiver already has errors reported, consider it valid to avoid
1788    // unnecessary errors (#58712).
1789    receiver_ty.error_reported()?;
1790
1791    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1792        Some(ArbitrarySelfTypesLevel::WithPointers)
1793    } else if tcx.features().arbitrary_self_types() {
1794        Some(ArbitrarySelfTypesLevel::Basic)
1795    } else {
1796        None
1797    };
1798    let generics = tcx.generics_of(method.def_id);
1799
1800    let receiver_validity =
1801        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1802    if let Err(receiver_validity_err) = receiver_validity {
1803        return Err(match arbitrary_self_types_level {
1804            // Wherever possible, emit a message advising folks that the features
1805            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1806            // have helped.
1807            None if receiver_is_valid(
1808                wfcx,
1809                span,
1810                receiver_ty,
1811                self_ty,
1812                Some(ArbitrarySelfTypesLevel::Basic),
1813                generics,
1814            )
1815            .is_ok() =>
1816            {
1817                // Report error; would have worked with `arbitrary_self_types`.
1818                feature_err(
1819                    &tcx.sess,
1820                    sym::arbitrary_self_types,
1821                    span,
1822                    format!(
1823                        "`{receiver_ty}` cannot be used as the type of `self` without \
1824                            the `arbitrary_self_types` feature",
1825                    ),
1826                )
1827                .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1828                .emit()
1829            }
1830            None | Some(ArbitrarySelfTypesLevel::Basic)
1831                if receiver_is_valid(
1832                    wfcx,
1833                    span,
1834                    receiver_ty,
1835                    self_ty,
1836                    Some(ArbitrarySelfTypesLevel::WithPointers),
1837                    generics,
1838                )
1839                .is_ok() =>
1840            {
1841                // Report error; would have worked with `arbitrary_self_types_pointers`.
1842                feature_err(
1843                    &tcx.sess,
1844                    sym::arbitrary_self_types_pointers,
1845                    span,
1846                    format!(
1847                        "`{receiver_ty}` cannot be used as the type of `self` without \
1848                            the `arbitrary_self_types_pointers` feature",
1849                    ),
1850                )
1851                .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1852                .emit()
1853            }
1854            _ =>
1855            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1856            {
1857                match receiver_validity_err {
1858                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1859                        let hint = match receiver_ty
1860                            .builtin_deref(false)
1861                            .unwrap_or(receiver_ty)
1862                            .ty_adt_def()
1863                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1864                        {
1865                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1866                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1867                            _ => None,
1868                        };
1869
1870                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1871                    }
1872                    ReceiverValidityError::DoesNotDeref => {
1873                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1874                            span,
1875                            receiver_ty,
1876                        })
1877                    }
1878                    ReceiverValidityError::MethodGenericParamUsed => {
1879                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1880                    }
1881                }
1882            }
1883        });
1884    }
1885    Ok(())
1886}
1887
1888/// Error cases which may be returned from `receiver_is_valid`. These error
1889/// cases are generated in this function as they may be unearthed as we explore
1890/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1891enum ReceiverValidityError {
1892    /// The self type does not get to the receiver type by following the
1893    /// autoderef chain.
1894    DoesNotDeref,
1895    /// A type was found which is a method type parameter, and that's not allowed.
1896    MethodGenericParamUsed,
1897}
1898
1899/// Confirms that a type is not a type parameter referring to one of the
1900/// method's type params.
1901fn confirm_type_is_not_a_method_generic_param(
1902    ty: Ty<'_>,
1903    method_generics: &ty::Generics,
1904) -> Result<(), ReceiverValidityError> {
1905    if let ty::Param(param) = ty.kind() {
1906        if (param.index as usize) >= method_generics.parent_count {
1907            return Err(ReceiverValidityError::MethodGenericParamUsed);
1908        }
1909    }
1910    Ok(())
1911}
1912
1913/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1914/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1915/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1916/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1917/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1918///
1919/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1920/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1921/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1922fn receiver_is_valid<'tcx>(
1923    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1924    span: Span,
1925    receiver_ty: Ty<'tcx>,
1926    self_ty: Ty<'tcx>,
1927    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1928    method_generics: &ty::Generics,
1929) -> Result<(), ReceiverValidityError> {
1930    let infcx = wfcx.infcx;
1931    let tcx = wfcx.tcx();
1932    let cause =
1933        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1934
1935    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1936    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1937        let ocx = ObligationCtxt::new(wfcx.infcx);
1938        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1939        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1940            Ok(())
1941        } else {
1942            Err(NoSolution)
1943        }
1944    }) {
1945        return Ok(());
1946    }
1947
1948    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1949
1950    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1951
1952    // The `arbitrary_self_types` feature allows custom smart pointer
1953    // types to be method receivers, as identified by following the Receiver<Target=T>
1954    // chain.
1955    if arbitrary_self_types_enabled.is_some() {
1956        autoderef = autoderef.use_receiver_trait();
1957    }
1958
1959    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1960    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1961        autoderef = autoderef.include_raw_pointers();
1962    }
1963
1964    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1965    while let Some((potential_self_ty, _)) = autoderef.next() {
1966        {
    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:1966",
                        "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(1966u32),
                        ::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!(
1967            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1968            potential_self_ty, self_ty
1969        );
1970
1971        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1972
1973        // Check if the self type unifies. If it does, then commit the result
1974        // since it may have region side-effects.
1975        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1976            let ocx = ObligationCtxt::new(wfcx.infcx);
1977            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1978            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1979                Ok(())
1980            } else {
1981                Err(NoSolution)
1982            }
1983        }) {
1984            wfcx.register_obligations(autoderef.into_obligations());
1985            return Ok(());
1986        }
1987
1988        // Without `feature(arbitrary_self_types)`, we require that each step in the
1989        // deref chain implement `LegacyReceiver`.
1990        if arbitrary_self_types_enabled.is_none() {
1991            let legacy_receiver_trait_def_id =
1992                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1993            if !legacy_receiver_is_implemented(
1994                wfcx,
1995                legacy_receiver_trait_def_id,
1996                cause.clone(),
1997                potential_self_ty,
1998            ) {
1999                // We cannot proceed.
2000                break;
2001            }
2002
2003            // Register the bound, in case it has any region side-effects.
2004            wfcx.register_bound(
2005                cause.clone(),
2006                wfcx.param_env,
2007                potential_self_ty,
2008                legacy_receiver_trait_def_id,
2009            );
2010        }
2011    }
2012
2013    {
    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:2013",
                        "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(2013u32),
                        ::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);
2014    Err(ReceiverValidityError::DoesNotDeref)
2015}
2016
2017fn legacy_receiver_is_implemented<'tcx>(
2018    wfcx: &WfCheckingCtxt<'_, 'tcx>,
2019    legacy_receiver_trait_def_id: DefId,
2020    cause: ObligationCause<'tcx>,
2021    receiver_ty: Ty<'tcx>,
2022) -> bool {
2023    let tcx = wfcx.tcx();
2024    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2025
2026    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2027
2028    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2029        true
2030    } else {
2031        {
    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:2031",
                        "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(2031u32),
                        ::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!(
2032            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2033            receiver_ty
2034        );
2035        false
2036    }
2037}
2038
2039pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2040    match tcx.def_kind(def_id) {
2041        DefKind::Enum | DefKind::Struct | DefKind::Union => {
2042            // Ok
2043        }
2044        DefKind::TyAlias => {
2045            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!(
2046                tcx.type_alias_is_lazy(def_id),
2047                "should not be computing variance of non-free type alias"
2048            );
2049        }
2050        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:?}"),
2051    }
2052
2053    let ty_predicates = tcx.predicates_of(def_id);
2054    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);
2055    let variances = tcx.variances_of(def_id);
2056
2057    let mut constrained_parameters: FxHashSet<_> = variances
2058        .iter()
2059        .enumerate()
2060        .filter(|&(_, &variance)| variance != ty::Bivariant)
2061        .map(|(index, _)| Parameter(index as u32))
2062        .collect();
2063
2064    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2065
2066    // Lazily calculated because it is only needed in case of an error.
2067    let explicitly_bounded_params = LazyCell::new(|| {
2068        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2069        tcx.hir_node_by_def_id(def_id)
2070            .generics()
2071            .unwrap()
2072            .predicates
2073            .iter()
2074            .filter_map(|predicate| match predicate.kind {
2075                hir::WherePredicateKind::BoundPredicate(predicate) => {
2076                    match icx.lower_ty(predicate.bounded_ty).kind() {
2077                        ty::Param(data) => Some(Parameter(data.index)),
2078                        _ => None,
2079                    }
2080                }
2081                _ => None,
2082            })
2083            .collect::<FxHashSet<_>>()
2084    });
2085
2086    for (index, _) in variances.iter().enumerate() {
2087        let parameter = Parameter(index as u32);
2088
2089        if constrained_parameters.contains(&parameter) {
2090            continue;
2091        }
2092
2093        let node = tcx.hir_node_by_def_id(def_id);
2094        let item = node.expect_item();
2095        let hir_generics = node.generics().unwrap();
2096        let hir_param = &hir_generics.params[index];
2097
2098        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2099
2100        if ty_param.def_id != hir_param.def_id.into() {
2101            // Valid programs always have lifetimes before types in the generic parameter list.
2102            // ty_generics are normalized to be in this required order, and variances are built
2103            // from ty generics, not from hir generics. but we need hir generics to get
2104            // a span out.
2105            //
2106            // If they aren't in the same order, then the user has written invalid code, and already
2107            // got an error about it (or I'm wrong about this).
2108            tcx.dcx().span_delayed_bug(
2109                hir_param.span,
2110                "hir generics and ty generics in different order",
2111            );
2112            continue;
2113        }
2114
2115        // Look for `ErrorGuaranteed` deeply within this type.
2116        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2117            .type_of(def_id)
2118            .instantiate_identity()
2119            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2120        {
2121            continue;
2122        }
2123
2124        match hir_param.name {
2125            hir::ParamName::Error(_) => {
2126                // Don't report a bivariance error for a lifetime that isn't
2127                // even valid to name.
2128            }
2129            _ => {
2130                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2131                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2132            }
2133        }
2134    }
2135}
2136
2137/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2138struct HasErrorDeep<'tcx> {
2139    tcx: TyCtxt<'tcx>,
2140    seen: FxHashSet<DefId>,
2141}
2142impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2143    type Result = ControlFlow<ErrorGuaranteed>;
2144
2145    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2146        match *ty.kind() {
2147            ty::Adt(def, _) => {
2148                if self.seen.insert(def.did()) {
2149                    for field in def.all_fields() {
2150                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2151                    }
2152                }
2153            }
2154            ty::Error(guar) => return ControlFlow::Break(guar),
2155            _ => {}
2156        }
2157        ty.super_visit_with(self)
2158    }
2159
2160    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2161        if let Err(guar) = r.error_reported() {
2162            ControlFlow::Break(guar)
2163        } else {
2164            ControlFlow::Continue(())
2165        }
2166    }
2167
2168    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2169        if let Err(guar) = c.error_reported() {
2170            ControlFlow::Break(guar)
2171        } else {
2172            ControlFlow::Continue(())
2173        }
2174    }
2175}
2176
2177fn report_bivariance<'tcx>(
2178    tcx: TyCtxt<'tcx>,
2179    param: &'tcx hir::GenericParam<'tcx>,
2180    has_explicit_bounds: bool,
2181    item: &'tcx hir::Item<'tcx>,
2182) -> ErrorGuaranteed {
2183    let param_name = param.name.ident();
2184
2185    let help = match item.kind {
2186        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2187            if let Some(def_id) = tcx.lang_items().phantom_data() {
2188                errors::UnusedGenericParameterHelp::Adt {
2189                    param_name,
2190                    phantom_data: tcx.def_path_str(def_id),
2191                }
2192            } else {
2193                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2194            }
2195        }
2196        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2197        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:?}"),
2198    };
2199
2200    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2201    intravisit::walk_item(
2202        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2203        item,
2204    );
2205
2206    if !usage_spans.is_empty() {
2207        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2208        // not actually looking into substitutions, just walking through fields / the "RHS".
2209        // We don't recurse into the hidden types of opaques or anything else fancy.
2210        let item_def_id = item.owner_id.to_def_id();
2211        let is_probably_cyclical =
2212            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2213                .visit_def(item_def_id)
2214                .is_break();
2215        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2216        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2217        // alias, and we should call those parameter usages recursive rather than just saying
2218        // they're unused...
2219        //
2220        // We currently report *all* of the parameter usages, since computing the exact
2221        // subset is very involved, and the fact we're mentioning recursion at all is
2222        // likely to guide the user in the right direction.
2223        if is_probably_cyclical {
2224            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2225                spans: usage_spans,
2226                param_span: param.span,
2227                param_name,
2228                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2229                help,
2230                note: (),
2231            });
2232        }
2233    }
2234
2235    let const_param_help =
2236        #[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);
2237
2238    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2239        span: param.span,
2240        param_name,
2241        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2242        usage_spans,
2243        help,
2244        const_param_help,
2245    });
2246    diag.code(E0392);
2247    if item.kind.recovered() {
2248        // Silence potentially redundant error, as the item had a parse error.
2249        diag.delay_as_bug()
2250    } else {
2251        diag.emit()
2252    }
2253}
2254
2255/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2256/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2257/// cyclical.
2258///
2259/// Notably, we don't consider substitutions here, so this may have false positives.
2260struct IsProbablyCyclical<'tcx> {
2261    tcx: TyCtxt<'tcx>,
2262    item_def_id: DefId,
2263    seen: FxHashSet<DefId>,
2264}
2265
2266impl<'tcx> IsProbablyCyclical<'tcx> {
2267    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2268        match self.tcx.def_kind(def_id) {
2269            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2270                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2271                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2272                })
2273            }
2274            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2275                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2276            }
2277            _ => ControlFlow::Continue(()),
2278        }
2279    }
2280}
2281
2282impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2283    type Result = ControlFlow<(), ()>;
2284
2285    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2286        let def_id = match ty.kind() {
2287            ty::Adt(adt_def, _) => Some(adt_def.did()),
2288            &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, .. }) => Some(def_id),
2289            _ => None,
2290        };
2291        if let Some(def_id) = def_id {
2292            if def_id == self.item_def_id {
2293                return ControlFlow::Break(());
2294            }
2295            if self.seen.insert(def_id) {
2296                self.visit_def(def_id)?;
2297            }
2298        }
2299        ty.super_visit_with(self)
2300    }
2301}
2302
2303/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2304///
2305/// This is used to report places where the user has used parameters in a
2306/// non-variance-constraining way for better bivariance errors.
2307struct CollectUsageSpans<'a> {
2308    spans: &'a mut Vec<Span>,
2309    param_def_id: DefId,
2310}
2311
2312impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2313    type Result = ();
2314
2315    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2316        // Skip the generics. We only care about fields, not where clause/param bounds.
2317    }
2318
2319    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2320        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2321            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2322                && def_id == self.param_def_id
2323            {
2324                self.spans.push(t.span);
2325                return;
2326            } else if let Res::SelfTyAlias { .. } = qpath.res {
2327                self.spans.push(t.span);
2328                return;
2329            }
2330        }
2331        intravisit::walk_ty(self, t);
2332    }
2333}
2334
2335impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2336    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2337    /// aren't true.
2338    #[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(2338u32),
                                    ::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))]
2339    fn check_false_global_bounds(&mut self) {
2340        let tcx = self.ocx.infcx.tcx;
2341        let mut span = tcx.def_span(self.body_def_id);
2342        let empty_env = ty::ParamEnv::empty();
2343
2344        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2345        // Check elaborated bounds.
2346        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2347
2348        for (pred, obligation_span) in implied_obligations {
2349            match pred.kind().skip_binder() {
2350                // We lower empty bounds like `Vec<dyn Copy>:` as
2351                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2352                // regular WF checking
2353                ty::ClauseKind::WellFormed(..)
2354                // Unstable feature goals cannot be proven in an empty environment so skip them
2355                | ty::ClauseKind::UnstableFeature(..) => continue,
2356                _ => {}
2357            }
2358
2359            // Match the existing behavior.
2360            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2361                let pred = self.normalize(span, None, pred);
2362
2363                // only use the span of the predicate clause (#90869)
2364                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2365                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2366                    span = predicates
2367                        .iter()
2368                        // There seems to be no better way to find out which predicate we are in
2369                        .find(|pred| pred.span.contains(obligation_span))
2370                        .map(|pred| pred.span)
2371                        .unwrap_or(obligation_span);
2372                }
2373
2374                let obligation = Obligation::new(
2375                    tcx,
2376                    traits::ObligationCause::new(
2377                        span,
2378                        self.body_def_id,
2379                        ObligationCauseCode::TrivialBound,
2380                    ),
2381                    empty_env,
2382                    pred,
2383                );
2384                self.ocx.register_obligation(obligation);
2385            }
2386        }
2387    }
2388}
2389
2390pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2391    let items = tcx.hir_crate_items(());
2392    let res =
2393        items
2394            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2395            .and(
2396                items.par_impl_items(|item| {
2397                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2398                }),
2399            )
2400            .and(items.par_trait_items(|item| {
2401                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2402            }))
2403            .and(items.par_foreign_items(|item| {
2404                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2405            }))
2406            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2407            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2408
2409    super::entry::check_for_entry_fn(tcx)?;
2410
2411    res
2412}
2413
2414fn lint_redundant_lifetimes<'tcx>(
2415    tcx: TyCtxt<'tcx>,
2416    owner_id: LocalDefId,
2417    outlives_env: &OutlivesEnvironment<'tcx>,
2418) {
2419    let def_kind = tcx.def_kind(owner_id);
2420    match def_kind {
2421        DefKind::Struct
2422        | DefKind::Union
2423        | DefKind::Enum
2424        | DefKind::Trait
2425        | DefKind::TraitAlias
2426        | DefKind::Fn
2427        | DefKind::Const { .. }
2428        | DefKind::Impl { of_trait: _ } => {
2429            // Proceed
2430        }
2431        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2432            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2433                // Don't check for redundant lifetimes for associated items of trait
2434                // implementations, since the signature is required to be compatible
2435                // with the trait, even if the implementation implies some lifetimes
2436                // are redundant.
2437                return;
2438            }
2439        }
2440        DefKind::Mod
2441        | DefKind::Variant
2442        | DefKind::TyAlias
2443        | DefKind::ForeignTy
2444        | DefKind::TyParam
2445        | DefKind::ConstParam
2446        | DefKind::Static { .. }
2447        | DefKind::Ctor(_, _)
2448        | DefKind::Macro(_)
2449        | DefKind::ExternCrate
2450        | DefKind::Use
2451        | DefKind::ForeignMod
2452        | DefKind::AnonConst
2453        | DefKind::InlineConst
2454        | DefKind::OpaqueTy
2455        | DefKind::Field
2456        | DefKind::LifetimeParam
2457        | DefKind::GlobalAsm
2458        | DefKind::Closure
2459        | DefKind::SyntheticCoroutineBody => return,
2460    }
2461
2462    // The ordering of this lifetime map is a bit subtle.
2463    //
2464    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2465    // where we can prove that `'candidate = 'victim`.
2466    //
2467    // `'static` must come first in this list because we can never replace `'static` with
2468    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2469    // suggest replacing `'a` with `'static`.
2470    let mut lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tcx.lifetimes.re_static]))vec![tcx.lifetimes.re_static];
2471    lifetimes.extend(
2472        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2473    );
2474    // If we are in a function, add its late-bound lifetimes too.
2475    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2476        for (idx, var) in
2477            tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2478        {
2479            let ty::BoundVariableKind::Region(kind) = var else { continue };
2480            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2481            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2482        }
2483    }
2484    lifetimes.retain(|candidate| candidate.is_named(tcx));
2485
2486    // Keep track of lifetimes which have already been replaced with other lifetimes.
2487    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2488    // both `'a` and `'b`.
2489    let mut shadowed = FxHashSet::default();
2490
2491    for (idx, &candidate) in lifetimes.iter().enumerate() {
2492        // Don't suggest removing a lifetime twice. We only need to check this
2493        // here and not up in the `victim` loop because equality is transitive,
2494        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2495        // A's victim loop.
2496        if shadowed.contains(&candidate) {
2497            continue;
2498        }
2499
2500        for &victim in &lifetimes[(idx + 1)..] {
2501            // All region parameters should have a `DefId` available as:
2502            // - Late-bound parameters should be of the`BrNamed` variety,
2503            // since we get these signatures straight from `hir_lowering`.
2504            // - Early-bound parameters unconditionally have a `DefId` available.
2505            //
2506            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2507            // can't really suggest to remove them.
2508            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2509                continue;
2510            };
2511
2512            // Do not rename lifetimes not local to this item since they'll overlap
2513            // with the lint running on the parent. We still want to consider parent
2514            // lifetimes which make child lifetimes redundant, otherwise we would
2515            // have truncated the `identity_for_item` args above.
2516            if tcx.parent(def_id) != owner_id.to_def_id() {
2517                continue;
2518            }
2519
2520            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2521            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2522                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2523            {
2524                shadowed.insert(victim);
2525                tcx.emit_node_span_lint(
2526                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2527                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2528                    tcx.def_span(def_id),
2529                    RedundantLifetimeArgsLint { candidate, victim },
2530                );
2531            }
2532        }
2533    }
2534}
2535
2536#[derive(const _: () =
    {
        impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
            RedundantLifetimeArgsLint<'tcx> where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    RedundantLifetimeArgsLint {
                        victim: __binding_0, candidate: __binding_1 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unnecessary lifetime parameter `{$victim}`")));
                        diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")));
                        ;
                        diag.arg("victim", __binding_0);
                        diag.arg("candidate", __binding_1);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
2537#[diag("unnecessary lifetime parameter `{$victim}`")]
2538#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2539struct RedundantLifetimeArgsLint<'tcx> {
2540    /// The lifetime we have found to be redundant.
2541    victim: ty::Region<'tcx>,
2542    // The lifetime we can replace the victim with.
2543    candidate: ty::Region<'tcx>,
2544}