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