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