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, RegionExt, RegionUtilitiesExt, Ty,
26    TyCtxt, TypeFlags, TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
27    TypeVisitor, TypingMode, Unnormalized, Upcast,
28};
29use rustc_middle::{bug, span_bug};
30use rustc_session::diagnostics::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 enforced on checked 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_checked(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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("assumed_wf_types")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("assumed_wf_types");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&assumed_wf_types)
                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item.owner_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item.owner_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item.name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item.name");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item.owner_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
                                                        as &dyn ::tracing::field::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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("item.owner_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("item.owner_id");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("item.name")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("item.name");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item.owner_id)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
                                            as &dyn ::tracing::field::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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("required_bounds")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("required_bounds");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&required_bounds)
                                            as &dyn ::tracing::field::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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty_idx")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty_idx");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("region_a_idx")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("region_a_idx");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_idx)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_a_idx)
                                            as &dyn ::tracing::field::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
                                                    ty, region_a) as &dyn ::tracing::field::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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("region_a_idx")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("region_a_idx");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("region_b_idx")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("region_b_idx");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_a_idx)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_b_idx)
                                            as &dyn ::tracing::field::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
                                                    region_a, region_b) as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
                                                    bounds) as &dyn ::tracing::field::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(def_id) => (*def_id, tcx.item_name(*def_id)),
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(def_id) => (*def_id, tcx.item_name(*def_id)),
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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("should_check_for_sync")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("should_check_for_sync");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&should_check_for_sync
                                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("has_value")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("has_value");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&has_value as
                                                            &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::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(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("obligations");
                                                                            NAME.as_str()
                                                                        }], ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::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(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        // Check that the argument is a tuple and is sized
1657        if let Some(ty) = inputs.next() {
1658            wfcx.register_bound(
1659                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1660                wfcx.param_env,
1661                *ty,
1662                tcx.require_lang_item(hir::LangItem::Tuple, span),
1663            );
1664            wfcx.register_bound(
1665                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1666                wfcx.param_env,
1667                *ty,
1668                tcx.require_lang_item(hir::LangItem::Sized, span),
1669            );
1670        } else {
1671            tcx.dcx().span_err(
1672                hir_decl.inputs.last().map_or(span, |input| input.span),
1673                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1674            );
1675        }
1676        // No more inputs other than the `self` type and the tuple type
1677        if inputs.next().is_some() {
1678            tcx.dcx().span_err(
1679                hir_decl.inputs.last().map_or(span, |input| input.span),
1680                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1681            );
1682        }
1683    }
1684
1685    // If the function has a body, additionally require that the return type is sized.
1686    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1687        let span = match hir_decl.output {
1688            hir::FnRetTy::Return(ty) => ty.span,
1689            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1690        };
1691
1692        wfcx.register_bound(
1693            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1694            wfcx.param_env,
1695            sig.output(),
1696            tcx.require_lang_item(LangItem::Sized, span),
1697        );
1698    }
1699}
1700
1701/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1702#[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)]
1703enum ArbitrarySelfTypesLevel {
1704    Basic,        // just arbitrary_self_types
1705    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1706}
1707
1708#[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(1708u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("method")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("method");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::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:1728",
                                    "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(1728u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_method_receiver: sig={0:?}",
                                                                sig) as &dyn ::tracing::field::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))]
1709fn check_method_receiver<'tcx>(
1710    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1711    fn_sig: &hir::FnSig<'_>,
1712    method: ty::AssocItem,
1713    self_ty: Ty<'tcx>,
1714) -> Result<(), ErrorGuaranteed> {
1715    let tcx = wfcx.tcx();
1716
1717    if !method.is_method() {
1718        return Ok(());
1719    }
1720
1721    let span = fn_sig.decl.inputs[0].span;
1722    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1723
1724    let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1725    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1726    let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1727
1728    debug!("check_method_receiver: sig={:?}", sig);
1729
1730    let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1731
1732    let receiver_ty = sig.inputs()[0];
1733    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1734
1735    // If the receiver already has errors reported, consider it valid to avoid
1736    // unnecessary errors (#58712).
1737    receiver_ty.error_reported()?;
1738
1739    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1740        Some(ArbitrarySelfTypesLevel::WithPointers)
1741    } else if tcx.features().arbitrary_self_types() {
1742        Some(ArbitrarySelfTypesLevel::Basic)
1743    } else {
1744        None
1745    };
1746    let generics = tcx.generics_of(method.def_id);
1747
1748    let receiver_validity =
1749        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1750    if let Err(receiver_validity_err) = receiver_validity {
1751        return Err(match arbitrary_self_types_level {
1752            // Wherever possible, emit a message advising folks that the features
1753            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1754            // have helped.
1755            None if receiver_is_valid(
1756                wfcx,
1757                span,
1758                receiver_ty,
1759                self_ty,
1760                Some(ArbitrarySelfTypesLevel::Basic),
1761                generics,
1762            )
1763            .is_ok() =>
1764            {
1765                // Report error; would have worked with `arbitrary_self_types`.
1766                feature_err(
1767                    &tcx.sess,
1768                    sym::arbitrary_self_types,
1769                    span,
1770                    format!(
1771                        "`{receiver_ty}` cannot be used as the type of `self` without \
1772                            the `arbitrary_self_types` feature",
1773                    ),
1774                )
1775                .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>`"))
1776                .emit()
1777            }
1778            None | Some(ArbitrarySelfTypesLevel::Basic)
1779                if receiver_is_valid(
1780                    wfcx,
1781                    span,
1782                    receiver_ty,
1783                    self_ty,
1784                    Some(ArbitrarySelfTypesLevel::WithPointers),
1785                    generics,
1786                )
1787                .is_ok() =>
1788            {
1789                // Report error; would have worked with `arbitrary_self_types_pointers`.
1790                feature_err(
1791                    &tcx.sess,
1792                    sym::arbitrary_self_types_pointers,
1793                    span,
1794                    format!(
1795                        "`{receiver_ty}` cannot be used as the type of `self` without \
1796                            the `arbitrary_self_types_pointers` feature",
1797                    ),
1798                )
1799                .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>`"))
1800                .emit()
1801            }
1802            _ =>
1803            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1804            {
1805                match receiver_validity_err {
1806                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1807                        let hint = match receiver_ty
1808                            .builtin_deref(false)
1809                            .unwrap_or(receiver_ty)
1810                            .ty_adt_def()
1811                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1812                        {
1813                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1814                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1815                            _ => None,
1816                        };
1817
1818                        tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1819                            span,
1820                            receiver_ty,
1821                            hint,
1822                        })
1823                    }
1824                    ReceiverValidityError::DoesNotDeref => {
1825                        tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1826                            span,
1827                            receiver_ty,
1828                        })
1829                    }
1830                    ReceiverValidityError::MethodGenericParamUsed => tcx
1831                        .dcx()
1832                        .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
1833                }
1834            }
1835        });
1836    }
1837    Ok(())
1838}
1839
1840/// Error cases which may be returned from `receiver_is_valid`. These error
1841/// cases are generated in this function as they may be unearthed as we explore
1842/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1843enum ReceiverValidityError {
1844    /// The self type does not get to the receiver type by following the
1845    /// autoderef chain.
1846    DoesNotDeref,
1847    /// A type was found which is a method type parameter, and that's not allowed.
1848    MethodGenericParamUsed,
1849}
1850
1851/// Confirms that a type is not a type parameter referring to one of the
1852/// method's type params.
1853fn confirm_type_is_not_a_method_generic_param(
1854    ty: Ty<'_>,
1855    method_generics: &ty::Generics,
1856) -> Result<(), ReceiverValidityError> {
1857    if let ty::Param(param) = ty.kind() {
1858        if (param.index as usize) >= method_generics.parent_count {
1859            return Err(ReceiverValidityError::MethodGenericParamUsed);
1860        }
1861    }
1862    Ok(())
1863}
1864
1865/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1866/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1867/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1868/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1869/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1870///
1871/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1872/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1873/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1874fn receiver_is_valid<'tcx>(
1875    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1876    span: Span,
1877    receiver_ty: Ty<'tcx>,
1878    self_ty: Ty<'tcx>,
1879    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1880    method_generics: &ty::Generics,
1881) -> Result<(), ReceiverValidityError> {
1882    let infcx = wfcx.infcx;
1883    let tcx = wfcx.tcx();
1884    let cause =
1885        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1886
1887    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1888    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1889        let ocx = ObligationCtxt::new(wfcx.infcx);
1890        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1891        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1892            Ok(())
1893        } else {
1894            Err(NoSolution)
1895        }
1896    }) {
1897        return Ok(());
1898    }
1899
1900    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1901
1902    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1903
1904    // The `arbitrary_self_types` feature allows custom smart pointer
1905    // types to be method receivers, as identified by following the Receiver<Target=T>
1906    // chain.
1907    if arbitrary_self_types_enabled.is_some() {
1908        autoderef = autoderef.use_receiver_trait();
1909    }
1910
1911    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1912    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1913        autoderef = autoderef.include_raw_pointers();
1914    }
1915
1916    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1917    while let Some((potential_self_ty, _)) = autoderef.next() {
1918        {
    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:1918",
                        "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(1918u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
                                                    potential_self_ty, self_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1919            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1920            potential_self_ty, self_ty
1921        );
1922
1923        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1924
1925        // Check if the self type unifies. If it does, then commit the result
1926        // since it may have region side-effects.
1927        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1928            let ocx = ObligationCtxt::new(wfcx.infcx);
1929            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1930            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1931                Ok(())
1932            } else {
1933                Err(NoSolution)
1934            }
1935        }) {
1936            wfcx.register_obligations(autoderef.into_obligations());
1937            return Ok(());
1938        }
1939
1940        // Without `feature(arbitrary_self_types)`, we require that each step in the
1941        // deref chain implement `LegacyReceiver`.
1942        if arbitrary_self_types_enabled.is_none() {
1943            let legacy_receiver_trait_def_id =
1944                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1945            if !legacy_receiver_is_implemented(
1946                wfcx,
1947                legacy_receiver_trait_def_id,
1948                cause.clone(),
1949                potential_self_ty,
1950            ) {
1951                // We cannot proceed.
1952                break;
1953            }
1954
1955            // Register the bound, in case it has any region side-effects.
1956            wfcx.register_bound(
1957                cause.clone(),
1958                wfcx.param_env,
1959                potential_self_ty,
1960                legacy_receiver_trait_def_id,
1961            );
1962        }
1963    }
1964
1965    {
    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:1965",
                        "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(1965u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
                                                    receiver_ty, self_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1966    Err(ReceiverValidityError::DoesNotDeref)
1967}
1968
1969fn legacy_receiver_is_implemented<'tcx>(
1970    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1971    legacy_receiver_trait_def_id: DefId,
1972    cause: ObligationCause<'tcx>,
1973    receiver_ty: Ty<'tcx>,
1974) -> bool {
1975    let tcx = wfcx.tcx();
1976    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1977
1978    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1979
1980    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1981        true
1982    } else {
1983        {
    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:1983",
                        "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(1983u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
                                                    receiver_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1984            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1985            receiver_ty
1986        );
1987        false
1988    }
1989}
1990
1991pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1992    match tcx.def_kind(def_id) {
1993        DefKind::Enum | DefKind::Struct | DefKind::Union => {
1994            // Ok
1995        }
1996        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:?}"),
1997    }
1998
1999    let ty_predicates = tcx.predicates_of(def_id);
2000    {
    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);
2001    let variances = tcx.variances_of(def_id);
2002
2003    let mut constrained_parameters: FxHashSet<_> = variances
2004        .iter()
2005        .enumerate()
2006        .filter(|&(_, &variance)| variance != ty::Bivariant)
2007        .map(|(index, _)| Parameter(index as u32))
2008        .collect();
2009
2010    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2011
2012    // Lazily calculated because it is only needed in case of an error.
2013    let explicitly_bounded_params = LazyCell::new(|| {
2014        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2015        tcx.hir_node_by_def_id(def_id)
2016            .generics()
2017            .unwrap()
2018            .predicates
2019            .iter()
2020            .filter_map(|predicate| match predicate.kind {
2021                hir::WherePredicateKind::BoundPredicate(predicate) => {
2022                    match icx.lower_ty(predicate.bounded_ty).kind() {
2023                        ty::Param(data) => Some(Parameter(data.index)),
2024                        _ => None,
2025                    }
2026                }
2027                _ => None,
2028            })
2029            .collect::<FxHashSet<_>>()
2030    });
2031
2032    for (index, _) in variances.iter().enumerate() {
2033        let parameter = Parameter(index as u32);
2034
2035        if constrained_parameters.contains(&parameter) {
2036            continue;
2037        }
2038
2039        let node = tcx.hir_node_by_def_id(def_id);
2040        let item = node.expect_item();
2041        let hir_generics = node.generics().unwrap();
2042        let hir_param = &hir_generics.params[index];
2043
2044        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2045
2046        if ty_param.def_id != hir_param.def_id.into() {
2047            // Valid programs always have lifetimes before types in the generic parameter list.
2048            // ty_generics are normalized to be in this required order, and variances are built
2049            // from ty generics, not from hir generics. but we need hir generics to get
2050            // a span out.
2051            //
2052            // If they aren't in the same order, then the user has written invalid code, and already
2053            // got an error about it (or I'm wrong about this).
2054            tcx.dcx().span_delayed_bug(
2055                hir_param.span,
2056                "hir generics and ty generics in different order",
2057            );
2058            continue;
2059        }
2060
2061        // Look for `ErrorGuaranteed` deeply within this type.
2062        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2063            .type_of(def_id)
2064            .instantiate_identity()
2065            .skip_norm_wip()
2066            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2067        {
2068            continue;
2069        }
2070
2071        match hir_param.name {
2072            hir::ParamName::Error(_) => {
2073                // Don't report a bivariance error for a lifetime that isn't
2074                // even valid to name.
2075            }
2076            _ => {
2077                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2078                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2079            }
2080        }
2081    }
2082}
2083
2084/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2085struct HasErrorDeep<'tcx> {
2086    tcx: TyCtxt<'tcx>,
2087    seen: FxHashSet<DefId>,
2088}
2089impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2090    type Result = ControlFlow<ErrorGuaranteed>;
2091
2092    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2093        match *ty.kind() {
2094            ty::Adt(def, _) => {
2095                if self.seen.insert(def.did()) {
2096                    for field in def.all_fields() {
2097                        self.tcx
2098                            .type_of(field.did)
2099                            .instantiate_identity()
2100                            .skip_norm_wip()
2101                            .visit_with(self)?;
2102                    }
2103                }
2104            }
2105            ty::Error(guar) => return ControlFlow::Break(guar),
2106            _ => {}
2107        }
2108        ty.super_visit_with(self)
2109    }
2110
2111    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2112        if let Err(guar) = r.error_reported() {
2113            ControlFlow::Break(guar)
2114        } else {
2115            ControlFlow::Continue(())
2116        }
2117    }
2118
2119    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2120        if let Err(guar) = c.error_reported() {
2121            ControlFlow::Break(guar)
2122        } else {
2123            ControlFlow::Continue(())
2124        }
2125    }
2126}
2127
2128fn report_bivariance<'tcx>(
2129    tcx: TyCtxt<'tcx>,
2130    param: &'tcx hir::GenericParam<'tcx>,
2131    has_explicit_bounds: bool,
2132    item: &'tcx hir::Item<'tcx>,
2133) -> ErrorGuaranteed {
2134    let param_name = param.name.ident();
2135
2136    let help = match item.kind {
2137        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2138            if let Some(def_id) = tcx.lang_items().phantom_data() {
2139                diagnostics::UnusedGenericParameterHelp::Adt {
2140                    param_name,
2141                    phantom_data: tcx.def_path_str(def_id),
2142                }
2143            } else {
2144                diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2145            }
2146        }
2147        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:?}"),
2148    };
2149
2150    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2151    intravisit::walk_item(
2152        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2153        item,
2154    );
2155
2156    if !usage_spans.is_empty() {
2157        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2158        // not actually looking into substitutions, just walking through fields / the "RHS".
2159        // We don't recurse into the hidden types of opaques or anything else fancy.
2160        let item_def_id = item.owner_id.to_def_id();
2161        let is_probably_cyclical =
2162            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2163                .visit_def(item_def_id)
2164                .is_break();
2165        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2166        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2167        // alias, and we should call those parameter usages recursive rather than just saying
2168        // they're unused...
2169        //
2170        // We currently report *all* of the parameter usages, since computing the exact
2171        // subset is very involved, and the fact we're mentioning recursion at all is
2172        // likely to guide the user in the right direction.
2173        if is_probably_cyclical {
2174            return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2175                spans: usage_spans,
2176                param_span: param.span,
2177                param_name,
2178                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2179                help,
2180                note: (),
2181            });
2182        }
2183    }
2184
2185    let const_param_help =
2186        #[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);
2187
2188    let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2189        span: param.span,
2190        param_name,
2191        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2192        usage_spans,
2193        help,
2194        const_param_help,
2195    });
2196    diag.code(E0392);
2197    if item.kind.recovered() {
2198        // Silence potentially redundant error, as the item had a parse error.
2199        diag.delay_as_bug()
2200    } else {
2201        diag.emit()
2202    }
2203}
2204
2205/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2206/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2207/// cyclical.
2208///
2209/// Notably, we don't consider substitutions here, so this may have false positives.
2210struct IsProbablyCyclical<'tcx> {
2211    tcx: TyCtxt<'tcx>,
2212    item_def_id: DefId,
2213    seen: FxHashSet<DefId>,
2214}
2215
2216impl<'tcx> IsProbablyCyclical<'tcx> {
2217    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2218        match self.tcx.def_kind(def_id) {
2219            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2220                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2221                    self.tcx
2222                        .type_of(field.did)
2223                        .instantiate_identity()
2224                        .skip_norm_wip()
2225                        .visit_with(self)
2226                })
2227            }
2228            _ => ControlFlow::Continue(()),
2229        }
2230    }
2231}
2232
2233impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2234    type Result = ControlFlow<(), ()>;
2235
2236    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2237        if let Some(adt_def) = ty.ty_adt_def() {
2238            if adt_def.did() == self.item_def_id {
2239                return ControlFlow::Break(());
2240            }
2241            if self.seen.insert(adt_def.did()) {
2242                self.visit_def(adt_def.did())?;
2243            }
2244        }
2245        ty.super_visit_with(self)
2246    }
2247}
2248
2249/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2250///
2251/// This is used to report places where the user has used parameters in a
2252/// non-variance-constraining way for better bivariance errors.
2253struct CollectUsageSpans<'a> {
2254    spans: &'a mut Vec<Span>,
2255    param_def_id: DefId,
2256}
2257
2258impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2259    type Result = ();
2260
2261    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2262        // Skip the generics. We only care about fields, not where clause/param bounds.
2263    }
2264
2265    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2266        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2267            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2268                && def_id == self.param_def_id
2269            {
2270                self.spans.push(t.span);
2271                return;
2272            } else if let Res::SelfTyAlias { .. } = qpath.res {
2273                self.spans.push(t.span);
2274                return;
2275            }
2276        }
2277        intravisit::walk_ty(self, t);
2278    }
2279}
2280
2281impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2282    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2283    /// aren't true.
2284    #[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(2284u32),
                                    ::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_all(&[]) })
                } 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))]
2285    fn check_false_global_bounds(&mut self) {
2286        let tcx = self.ocx.infcx.tcx;
2287        let mut span = tcx.def_span(self.body_def_id);
2288        let empty_env = ty::ParamEnv::empty();
2289
2290        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2291        // Check elaborated bounds.
2292        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2293
2294        for (pred, obligation_span) in implied_obligations {
2295            match pred.kind().skip_binder() {
2296                // We lower empty bounds like `Vec<dyn Copy>:` as
2297                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2298                // regular WF checking
2299                ty::ClauseKind::WellFormed(..)
2300                // Unstable feature goals cannot be proven in an empty environment so skip them
2301                | ty::ClauseKind::UnstableFeature(..) => continue,
2302                _ => {}
2303            }
2304
2305            // Match the existing behavior.
2306            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2307                let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2308
2309                // only use the span of the predicate clause (#90869)
2310                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2311                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2312                    span = predicates
2313                        .iter()
2314                        // There seems to be no better way to find out which predicate we are in
2315                        .find(|pred| pred.span.contains(obligation_span))
2316                        .map(|pred| pred.span)
2317                        .unwrap_or(obligation_span);
2318                }
2319
2320                let obligation = Obligation::new(
2321                    tcx,
2322                    traits::ObligationCause::new(
2323                        span,
2324                        self.body_def_id,
2325                        ObligationCauseCode::TrivialBound,
2326                    ),
2327                    empty_env,
2328                    pred,
2329                );
2330                self.ocx.register_obligation(obligation);
2331            }
2332        }
2333    }
2334}
2335
2336pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2337    let items = tcx.hir_crate_items(());
2338    let res =
2339        items
2340            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2341            .and(
2342                items.par_impl_items(|item| {
2343                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2344                }),
2345            )
2346            .and(items.par_trait_items(|item| {
2347                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2348            }))
2349            .and(items.par_foreign_items(|item| {
2350                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2351            }))
2352            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2353            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2354
2355    super::entry::check_for_entry_fn(tcx)?;
2356
2357    res
2358}
2359
2360fn lint_redundant_lifetimes<'tcx>(
2361    tcx: TyCtxt<'tcx>,
2362    owner_id: LocalDefId,
2363    outlives_env: &OutlivesEnvironment<'tcx>,
2364) {
2365    let def_kind = tcx.def_kind(owner_id);
2366    match def_kind {
2367        DefKind::Struct
2368        | DefKind::Union
2369        | DefKind::Enum
2370        | DefKind::Trait
2371        | DefKind::TraitAlias
2372        | DefKind::Fn
2373        | DefKind::Const { .. }
2374        | DefKind::Impl { of_trait: _ } => {
2375            // Proceed
2376        }
2377        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2378            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2379                // Don't check for redundant lifetimes for associated items of trait
2380                // implementations, since the signature is required to be compatible
2381                // with the trait, even if the implementation implies some lifetimes
2382                // are redundant.
2383                return;
2384            }
2385        }
2386        DefKind::Mod
2387        | DefKind::Variant
2388        | DefKind::TyAlias
2389        | DefKind::ForeignTy
2390        | DefKind::TyParam
2391        | DefKind::ConstParam
2392        | DefKind::Static { .. }
2393        | DefKind::Ctor(_, _)
2394        | DefKind::Macro(_)
2395        | DefKind::ExternCrate
2396        | DefKind::Use
2397        | DefKind::ForeignMod
2398        | DefKind::AnonConst
2399        | DefKind::OpaqueTy
2400        | DefKind::Field
2401        | DefKind::LifetimeParam
2402        | DefKind::GlobalAsm
2403        | DefKind::Closure
2404        | DefKind::SyntheticCoroutineBody => return,
2405    }
2406
2407    // The ordering of this lifetime map is a bit subtle.
2408    //
2409    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2410    // where we can prove that `'candidate = 'victim`.
2411    //
2412    // `'static` must come first in this list because we can never replace `'static` with
2413    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2414    // suggest replacing `'a` with `'static`.
2415    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];
2416    lifetimes.extend(
2417        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2418    );
2419    // If we are in a function, add its late-bound lifetimes too.
2420    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2421        for (idx, var) in tcx
2422            .fn_sig(owner_id)
2423            .instantiate_identity()
2424            .skip_norm_wip()
2425            .bound_vars()
2426            .iter()
2427            .enumerate()
2428        {
2429            let ty::BoundVariableKind::Region(kind) = var else { continue };
2430            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2431            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2432        }
2433    }
2434    lifetimes.retain(|candidate| candidate.is_named(tcx));
2435
2436    // Keep track of lifetimes which have already been replaced with other lifetimes.
2437    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2438    // both `'a` and `'b`.
2439    let mut shadowed = FxHashSet::default();
2440
2441    for (idx, &candidate) in lifetimes.iter().enumerate() {
2442        // Don't suggest removing a lifetime twice. We only need to check this
2443        // here and not up in the `victim` loop because equality is transitive,
2444        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2445        // A's victim loop.
2446        if shadowed.contains(&candidate) {
2447            continue;
2448        }
2449
2450        for &victim in &lifetimes[(idx + 1)..] {
2451            // All region parameters should have a `DefId` available as:
2452            // - Late-bound parameters should be of the`BrNamed` variety,
2453            // since we get these signatures straight from `hir_lowering`.
2454            // - Early-bound parameters unconditionally have a `DefId` available.
2455            //
2456            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2457            // can't really suggest to remove them.
2458            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2459                continue;
2460            };
2461
2462            // Do not rename lifetimes not local to this item since they'll overlap
2463            // with the lint running on the parent. We still want to consider parent
2464            // lifetimes which make child lifetimes redundant, otherwise we would
2465            // have truncated the `identity_for_item` args above.
2466            if tcx.parent(def_id) != owner_id.to_def_id() {
2467                continue;
2468            }
2469
2470            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2471            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2472                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2473            {
2474                shadowed.insert(victim);
2475                tcx.emit_node_span_lint(
2476                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2477                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2478                    tcx.def_span(def_id),
2479                    RedundantLifetimeArgsLint { candidate, victim },
2480                );
2481            }
2482        }
2483    }
2484}
2485
2486#[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)]
2487#[diag("unnecessary lifetime parameter `{$victim}`")]
2488#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2489struct RedundantLifetimeArgsLint<'tcx> {
2490    /// The lifetime we have found to be redundant.
2491    victim: ty::Region<'tcx>,
2492    // The lifetime we can replace the victim with.
2493    candidate: ty::Region<'tcx>,
2494}