Skip to main content

rustc_hir_analysis/check/
wfcheck.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let loc = Some(WellFormedLoc::Ty(def_id));
            enter_wf_checking_ctxt(tcx, def_id,
                |wfcx|
                    {
                        let item = tcx.associated_item(def_id);
                        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
                        let self_ty =
                            match item.container {
                                ty::AssocContainer::Trait => tcx.types.self_param,
                                ty::AssocContainer::InherentImpl |
                                    ty::AssocContainer::TraitImpl(_) => {
                                    tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
                                }
                            };
                        let span = tcx.def_span(def_id);
                        match item.kind {
                            ty::AssocKind::Const { .. } => {
                                let ty = tcx.type_of(def_id).instantiate_identity();
                                let ty =
                                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                        ty);
                                wfcx.register_wf_obligation(span, loc, ty.into());
                                let has_value = item.defaultness(tcx).has_value();
                                if tcx.is_type_const(def_id) {
                                    check_type_const(wfcx, def_id, ty, has_value)?;
                                }
                                if has_value {
                                    let code = ObligationCauseCode::SizedConstOrStatic;
                                    wfcx.register_bound(ObligationCause::new(span, def_id,
                                            code), wfcx.param_env, ty,
                                        tcx.require_lang_item(LangItem::Sized, span));
                                }
                                Ok(())
                            }
                            ty::AssocKind::Fn { .. } => {
                                let sig =
                                    tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
                                let hir_sig =
                                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
                                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
                                check_method_receiver(wfcx, hir_sig, item, self_ty)
                            }
                            ty::AssocKind::Type { .. } => {
                                if let ty::AssocContainer::Trait = item.container {
                                    check_associated_type_bounds(wfcx, item, span)
                                }
                                if item.defaultness(tcx).has_value() {
                                    let ty = tcx.type_of(def_id).instantiate_identity();
                                    let ty =
                                        wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                            ty);
                                    wfcx.register_wf_obligation(span, loc, ty.into());
                                }
                                Ok(())
                            }
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
968pub(crate) fn check_associated_item(
969    tcx: TyCtxt<'_>,
970    def_id: LocalDefId,
971) -> Result<(), ErrorGuaranteed> {
972    let loc = Some(WellFormedLoc::Ty(def_id));
973    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
974        let item = tcx.associated_item(def_id);
975
976        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
977        // other `Foo` impls are incoherent.
978        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
979
980        let self_ty = match item.container {
981            ty::AssocContainer::Trait => tcx.types.self_param,
982            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
983                tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
984            }
985        };
986
987        let span = tcx.def_span(def_id);
988
989        match item.kind {
990            ty::AssocKind::Const { .. } => {
991                let ty = tcx.type_of(def_id).instantiate_identity();
992                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
993                wfcx.register_wf_obligation(span, loc, ty.into());
994
995                let has_value = item.defaultness(tcx).has_value();
996                if tcx.is_type_const(def_id) {
997                    check_type_const(wfcx, def_id, ty, has_value)?;
998                }
999
1000                if has_value {
1001                    let code = ObligationCauseCode::SizedConstOrStatic;
1002                    wfcx.register_bound(
1003                        ObligationCause::new(span, def_id, code),
1004                        wfcx.param_env,
1005                        ty,
1006                        tcx.require_lang_item(LangItem::Sized, span),
1007                    );
1008                }
1009
1010                Ok(())
1011            }
1012            ty::AssocKind::Fn { .. } => {
1013                let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1014                let hir_sig =
1015                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1016                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1017                check_method_receiver(wfcx, hir_sig, item, self_ty)
1018            }
1019            ty::AssocKind::Type { .. } => {
1020                if let ty::AssocContainer::Trait = item.container {
1021                    check_associated_type_bounds(wfcx, item, span)
1022                }
1023                if item.defaultness(tcx).has_value() {
1024                    let ty = tcx.type_of(def_id).instantiate_identity();
1025                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1026                    wfcx.register_wf_obligation(span, loc, ty.into());
1027                }
1028                Ok(())
1029            }
1030        }
1031    })
1032}
1033
1034/// In a type definition, we check that to ensure that the types of the fields are well-formed.
1035pub(crate) fn check_type_defn<'tcx>(
1036    tcx: TyCtxt<'tcx>,
1037    item: LocalDefId,
1038    all_sized: bool,
1039) -> Result<(), ErrorGuaranteed> {
1040    tcx.ensure_ok().check_representability(item);
1041    let adt_def = tcx.adt_def(item);
1042
1043    enter_wf_checking_ctxt(tcx, item, |wfcx| {
1044        let variants = adt_def.variants();
1045        let packed = adt_def.repr().packed();
1046
1047        for variant in variants.iter() {
1048            // All field types must be well-formed.
1049            for field in &variant.fields {
1050                if let Some(def_id) = field.value
1051                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1052                {
1053                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1054                    // be refactored to check the instantiate-ability of the code better.
1055                    if let Some(def_id) = def_id.as_local()
1056                        && let DefKind::AnonConst = tcx.def_kind(def_id)
1057                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1058                        && let expr = &tcx.hir_body(anon.body).value
1059                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1060                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1061                    {
1062                        // Do not evaluate bare `const` params, as those would ICE and are only
1063                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1064                    } else {
1065                        // Evaluate the constant proactively, to emit an error if the constant has
1066                        // an unconditional error. We only do so if the const has no type params.
1067                        let _ = tcx.const_eval_poly(def_id);
1068                    }
1069                }
1070                let field_id = field.did.expect_local();
1071                let span = tcx.ty_span(field_id);
1072                let ty = wfcx.deeply_normalize(
1073                    span,
1074                    None,
1075                    tcx.type_of(field.did).instantiate_identity(),
1076                );
1077                wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1078
1079                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())
1080                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1081                {
1082                    // Scalable vectors can only be fields of structs if the type has a
1083                    // `rustc_scalable_vector` attribute w/out specifying an element count
1084                    tcx.dcx().span_err(
1085                        span,
1086                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1087                            "scalable vectors cannot be fields of a {}",
1088                            adt_def.variant_descr()
1089                        ),
1090                    );
1091                }
1092            }
1093
1094            // For DST, or when drop needs to copy things around, all
1095            // intermediate types must be sized.
1096            let needs_drop_copy = || {
1097                packed && {
1098                    let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1099                    let ty = tcx.erase_and_anonymize_regions(ty);
1100                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1101                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1102                }
1103            };
1104            // All fields (except for possibly the last) should be sized.
1105            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1106            let unsized_len = if all_sized { 0 } else { 1 };
1107            for (idx, field) in
1108                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1109            {
1110                let last = idx == variant.fields.len() - 1;
1111                let span = tcx.ty_span(field.did.expect_local());
1112                let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1113                wfcx.register_bound(
1114                    traits::ObligationCause::new(
1115                        span,
1116                        wfcx.body_def_id,
1117                        ObligationCauseCode::FieldSized {
1118                            adt_kind: adt_def.adt_kind(),
1119                            span,
1120                            last,
1121                        },
1122                    ),
1123                    wfcx.param_env,
1124                    ty,
1125                    tcx.require_lang_item(LangItem::Sized, span),
1126                );
1127            }
1128
1129            // Explicit `enum` discriminant values must const-evaluate successfully.
1130            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1131                match tcx.const_eval_poly(discr_def_id) {
1132                    Ok(_) => {}
1133                    Err(ErrorHandled::Reported(..)) => {}
1134                    Err(ErrorHandled::TooGeneric(sp)) => {
1135                        ::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")
1136                    }
1137                }
1138            }
1139        }
1140
1141        check_where_clauses(wfcx, item);
1142        Ok(())
1143    })
1144}
1145
1146#[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(1146u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
                return Ok(());
            }
            let trait_def = tcx.trait_def(def_id);
            if trait_def.is_marker ||
                    #[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
                        {
                        TraitSpecializationKind::Marker => true,
                        _ => false,
                    } {
                for associated_def_id in &*tcx.associated_item_def_ids(def_id)
                    {
                    {
                            tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
                                        })).with_code(E0714)
                        }.emit();
                }
            }
            let res =
                enter_wf_checking_ctxt(tcx, def_id,
                    |wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
            res
        }
    }
}#[instrument(skip(tcx))]
1147pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1148    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1149        // `PointeeSized` is removed during lowering.
1150        return Ok(());
1151    }
1152
1153    let trait_def = tcx.trait_def(def_id);
1154    if trait_def.is_marker
1155        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1156    {
1157        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1158            struct_span_code_err!(
1159                tcx.dcx(),
1160                tcx.def_span(*associated_def_id),
1161                E0714,
1162                "marker traits cannot have associated items",
1163            )
1164            .emit();
1165        }
1166    }
1167
1168    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1169        check_where_clauses(wfcx, def_id);
1170        Ok(())
1171    });
1172
1173    res
1174}
1175
1176/// Checks all associated type defaults of trait `trait_def_id`.
1177///
1178/// Assuming the defaults are used, check that all predicates (bounds on the
1179/// assoc type and where clauses on the trait) hold.
1180fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1181    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1182
1183    {
    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:1183",
                        "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(1183u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
                                                    bounds) as &dyn Value))])
            });
    } else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1184    let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1185        |(bound, bound_span)| {
1186            traits::wf::clause_obligations(
1187                wfcx.infcx,
1188                wfcx.param_env,
1189                wfcx.body_def_id,
1190                bound,
1191                bound_span,
1192            )
1193        },
1194    );
1195
1196    wfcx.register_obligations(wf_obligations);
1197}
1198
1199fn check_item_fn(
1200    tcx: TyCtxt<'_>,
1201    def_id: LocalDefId,
1202    decl: &hir::FnDecl<'_>,
1203) -> Result<(), ErrorGuaranteed> {
1204    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1205        check_eiis_fn(tcx, def_id);
1206
1207        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1208        check_fn_or_method(wfcx, sig, decl, def_id);
1209        Ok(())
1210    })
1211}
1212
1213fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1214    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1215    // that was used to mark the implementation. This is a two step process.
1216    for EiiImpl { resolution, span, .. } in
1217        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                        break 'done Some(impls);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1218    {
1219        let (foreign_item, name) = match resolution {
1220            EiiImplResolution::Macro(def_id) => {
1221                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1222                // signature that we'd like to compare the function we're currently checking with
1223                if let Some(foreign_item) =
1224                    {
    {
        '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)
1225                {
1226                    (foreign_item, tcx.item_name(*def_id))
1227                } else {
1228                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1229                    continue;
1230                }
1231            }
1232            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1233            EiiImplResolution::Error(_eg) => continue,
1234        };
1235
1236        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1237    }
1238}
1239
1240fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1241    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1242    // that was used to mark the implementation. This is a two step process.
1243    for EiiImpl { resolution, span, .. } in
1244        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                        break 'done Some(impls);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1245    {
1246        let (foreign_item, name) = match resolution {
1247            EiiImplResolution::Macro(def_id) => {
1248                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1249                // signature that we'd like to compare the function we're currently checking with
1250                if let Some(foreign_item) =
1251                    {
    {
        '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)
1252                {
1253                    (foreign_item, tcx.item_name(*def_id))
1254                } else {
1255                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1256                    continue;
1257                }
1258            }
1259            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1260            EiiImplResolution::Error(_eg) => continue,
1261        };
1262
1263        let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1264    }
1265}
1266
1267#[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(1267u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item_id", "ty",
                                                    "should_check_for_sync"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&should_check_for_sync
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            enter_wf_checking_ctxt(tcx, item_id,
                |wfcx|
                    {
                        if should_check_for_sync {
                            check_eiis_static(tcx, item_id, ty);
                        }
                        let span = tcx.ty_span(item_id);
                        let loc = Some(WellFormedLoc::Ty(item_id));
                        let item_ty =
                            wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
                        let is_foreign_item = tcx.is_foreign_item(item_id);
                        let is_structurally_foreign_item =
                            ||
                                {
                                    let tail =
                                        tcx.struct_tail_raw(item_ty, &ObligationCause::dummy(),
                                            |ty| wfcx.deeply_normalize(span, loc, ty), || {});

                                    #[allow(non_exhaustive_omitted_patterns)]
                                    match tail.kind() { ty::Foreign(_) => true, _ => false, }
                                };
                        let forbid_unsized =
                            !(is_foreign_item && is_structurally_foreign_item());
                        wfcx.register_wf_obligation(span,
                            Some(WellFormedLoc::Ty(item_id)), item_ty.into());
                        if forbid_unsized {
                            let span = tcx.def_span(item_id);
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sized, span));
                        }
                        let should_check_for_sync =
                            should_check_for_sync && !is_foreign_item &&
                                    tcx.static_mutability(item_id.to_def_id()) ==
                                        Some(hir::Mutability::Not) &&
                                !tcx.is_thread_local_static(item_id.to_def_id());
                        if should_check_for_sync {
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SharedStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sync, span));
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
1268pub(crate) fn check_static_item<'tcx>(
1269    tcx: TyCtxt<'tcx>,
1270    item_id: LocalDefId,
1271    ty: Ty<'tcx>,
1272    should_check_for_sync: bool,
1273) -> Result<(), ErrorGuaranteed> {
1274    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1275        if should_check_for_sync {
1276            check_eiis_static(tcx, item_id, ty);
1277        }
1278
1279        let span = tcx.ty_span(item_id);
1280        let loc = Some(WellFormedLoc::Ty(item_id));
1281        let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1282
1283        let is_foreign_item = tcx.is_foreign_item(item_id);
1284        let is_structurally_foreign_item = || {
1285            let tail = tcx.struct_tail_raw(
1286                item_ty,
1287                &ObligationCause::dummy(),
1288                |ty| wfcx.deeply_normalize(span, loc, ty),
1289                || {},
1290            );
1291
1292            matches!(tail.kind(), ty::Foreign(_))
1293        };
1294        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1295
1296        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1297        if forbid_unsized {
1298            let span = tcx.def_span(item_id);
1299            wfcx.register_bound(
1300                traits::ObligationCause::new(
1301                    span,
1302                    wfcx.body_def_id,
1303                    ObligationCauseCode::SizedConstOrStatic,
1304                ),
1305                wfcx.param_env,
1306                item_ty,
1307                tcx.require_lang_item(LangItem::Sized, span),
1308            );
1309        }
1310
1311        // Ensure that the end result is `Sync` in a non-thread local `static`.
1312        let should_check_for_sync = should_check_for_sync
1313            && !is_foreign_item
1314            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1315            && !tcx.is_thread_local_static(item_id.to_def_id());
1316
1317        if should_check_for_sync {
1318            wfcx.register_bound(
1319                traits::ObligationCause::new(
1320                    span,
1321                    wfcx.body_def_id,
1322                    ObligationCauseCode::SharedStatic,
1323                ),
1324                wfcx.param_env,
1325                item_ty,
1326                tcx.require_lang_item(LangItem::Sync, span),
1327            );
1328        }
1329        Ok(())
1330    })
1331}
1332
1333#[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(1333u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "item_ty",
                                                    "has_value"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&has_value as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            let span = tcx.def_span(def_id);
            if !tcx.features().const_param_ty_unchecked() {
                wfcx.register_bound(ObligationCause::new(span, def_id,
                        ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
                    item_ty,
                    tcx.require_lang_item(LangItem::ConstParamTy, span));
            }
            if has_value {
                let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
                let norm_ct =
                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                        raw_ct);
                wfcx.register_wf_obligation(span,
                    Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
                wfcx.register_obligation(Obligation::new(tcx,
                        ObligationCause::new(span, def_id,
                            ObligationCauseCode::WellFormed(None)), wfcx.param_env,
                        ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
                                item_ty))));
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1334pub(super) fn check_type_const<'tcx>(
1335    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1336    def_id: LocalDefId,
1337    item_ty: Ty<'tcx>,
1338    has_value: bool,
1339) -> Result<(), ErrorGuaranteed> {
1340    let tcx = wfcx.tcx();
1341    let span = tcx.def_span(def_id);
1342
1343    if !tcx.features().const_param_ty_unchecked() {
1344        wfcx.register_bound(
1345            ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1346            wfcx.param_env,
1347            item_ty,
1348            tcx.require_lang_item(LangItem::ConstParamTy, span),
1349        );
1350    }
1351
1352    if has_value {
1353        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1354        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1355        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1356
1357        wfcx.register_obligation(Obligation::new(
1358            tcx,
1359            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1360            wfcx.param_env,
1361            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1362        ));
1363    }
1364    Ok(())
1365}
1366
1367#[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(1367u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = wfcx.infcx;
            let tcx = wfcx.tcx();
            let predicates = tcx.predicates_of(def_id.to_def_id());
            let generics = tcx.generics_of(def_id);
            for param in &generics.own_params {
                if let Some(default) =
                        param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
                    {
                    if !default.has_param() {
                        wfcx.register_wf_obligation(tcx.def_span(param.def_id),
                            (#[allow(non_exhaustive_omitted_patterns)] match param.kind
                                    {
                                    GenericParamDefKind::Type { .. } => true,
                                    _ => false,
                                }).then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
                            default.as_term().unwrap());
                    } else {
                        let GenericArgKind::Const(ct) =
                            default.kind() else { continue; };
                        let ct_ty =
                            match ct.kind() {
                                ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
                                    ty::ConstKind::Bound(_, _) =>
                                    ::core::panicking::panic("internal error: entered unreachable code"),
                                ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
                                    continue,
                                ty::ConstKind::Value(cv) => cv.ty,
                                ty::ConstKind::Unevaluated(uv) =>
                                    uv.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(pred).instantiate(tcx, args);
                                if instantiated_pred.skip_normalization().has_non_region_param()
                                            || param_count.params.len() > 1 || has_region {
                                    None
                                } else if predicates.predicates.iter().any(|&(p, _)|
                                            Unnormalized::new_wip(p) == instantiated_pred) {
                                    None
                                } else { Some((instantiated_pred, sp)) }
                            }).map(|(pred, sp)|
                        {
                            let pred = wfcx.normalize(sp, None, pred);
                            let cause =
                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                            Obligation::new(tcx, cause, wfcx.param_env, pred)
                        });
            let predicates = predicates.instantiate_identity(tcx);
            let assoc_const_obligations: Vec<_> =
                predicates.predicates.iter().copied().zip(predicates.spans.iter().copied()).filter_map(|(clause,
                                sp)|
                            {
                                let clause = clause.skip_norm_wip();
                                let proj = clause.as_projection_clause()?;
                                let pred_binder =
                                    proj.map_bound(|pred|
                                                {
                                                    pred.term.as_const().map(|ct|
                                                            {
                                                                let assoc_const_ty =
                                                                    tcx.type_of(pred.projection_term.def_id()).instantiate(tcx,
                                                                            pred.projection_term.args).skip_norm_wip();
                                                                ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
                                                            })
                                                }).transpose();
                                pred_binder.map(|pred_binder|
                                        {
                                            let cause =
                                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                                            Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
                                        })
                            }).collect();
            match (&predicates.predicates.len(), &predicates.spans.len()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let wf_obligations =
                predicates.into_iter().flat_map(|(p, sp)|
                        {
                            traits::wf::clause_obligations(infcx, wfcx.param_env,
                                wfcx.body_def_id, p.skip_norm_wip(), sp)
                        });
            let obligations: Vec<_> =
                wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
            wfcx.register_obligations(obligations);
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1464pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1465    let infcx = wfcx.infcx;
1466    let tcx = wfcx.tcx();
1467
1468    let predicates = tcx.predicates_of(def_id.to_def_id());
1469    let generics = tcx.generics_of(def_id);
1470
1471    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1472    // For example, this forbids the declaration:
1473    //
1474    //     struct Foo<T = Vec<[u32]>> { .. }
1475    //
1476    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1477    for param in &generics.own_params {
1478        if let Some(default) = param
1479            .default_value(tcx)
1480            .map(ty::EarlyBinder::instantiate_identity)
1481            .map(Unnormalized::skip_norm_wip)
1482        {
1483            // Ignore dependent defaults -- that is, where the default of one type
1484            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1485            // be sure if it will error or not as user might always specify the other.
1486            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1487            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1488            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1489            if !default.has_param() {
1490                wfcx.register_wf_obligation(
1491                    tcx.def_span(param.def_id),
1492                    matches!(param.kind, GenericParamDefKind::Type { .. })
1493                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1494                    default.as_term().unwrap(),
1495                );
1496            } else {
1497                // If we've got a generic const parameter we still want to check its
1498                // type is correct in case both it and the param type are fully concrete.
1499                let GenericArgKind::Const(ct) = default.kind() else {
1500                    continue;
1501                };
1502
1503                let ct_ty = match ct.kind() {
1504                    ty::ConstKind::Infer(_)
1505                    | ty::ConstKind::Placeholder(_)
1506                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1507                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1508                    ty::ConstKind::Value(cv) => cv.ty,
1509                    ty::ConstKind::Unevaluated(uv) => uv.type_of(infcx.tcx).skip_norm_wip(),
1510                    ty::ConstKind::Param(param_ct) => {
1511                        param_ct.find_const_ty_from_env(wfcx.param_env)
1512                    }
1513                };
1514
1515                let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1516                if !ct_ty.has_param() && !param_ty.has_param() {
1517                    let cause = traits::ObligationCause::new(
1518                        tcx.def_span(param.def_id),
1519                        wfcx.body_def_id,
1520                        ObligationCauseCode::WellFormed(None),
1521                    );
1522                    wfcx.register_obligation(Obligation::new(
1523                        tcx,
1524                        cause,
1525                        wfcx.param_env,
1526                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1527                    ));
1528                }
1529            }
1530        }
1531    }
1532
1533    // Check that trait predicates are WF when params are instantiated with their defaults.
1534    // We don't want to overly constrain the predicates that may be written but we want to
1535    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1536    // Therefore we check if a predicate which contains a single type param
1537    // with a concrete default is WF with that default instantiated.
1538    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1539    //
1540    // First we build the defaulted generic parameters.
1541    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1542        if param.index >= generics.parent_count as u32
1543            // If the param has a default, ...
1544            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1545            // ... and it's not a dependent default, ...
1546            && !default.has_param()
1547        {
1548            // ... then instantiate it with the default.
1549            return default;
1550        }
1551        tcx.mk_param_from_def(param)
1552    });
1553
1554    // Now we build the instantiated predicates.
1555    let default_obligations = predicates
1556        .predicates
1557        .iter()
1558        .flat_map(|&(pred, sp)| {
1559            #[derive(Default)]
1560            struct CountParams {
1561                params: FxHashSet<u32>,
1562            }
1563            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1564                type Result = ControlFlow<()>;
1565                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1566                    if let ty::Param(param) = t.kind() {
1567                        self.params.insert(param.index);
1568                    }
1569                    t.super_visit_with(self)
1570                }
1571
1572                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1573                    ControlFlow::Break(())
1574                }
1575
1576                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1577                    if let ty::ConstKind::Param(param) = c.kind() {
1578                        self.params.insert(param.index);
1579                    }
1580                    c.super_visit_with(self)
1581                }
1582            }
1583            let mut param_count = CountParams::default();
1584            let has_region = pred.visit_with(&mut param_count).is_break();
1585            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1586            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1587            // or preds with multiple params.
1588            if instantiated_pred.skip_normalization().has_non_region_param()
1589                || param_count.params.len() > 1
1590                || has_region
1591            {
1592                None
1593            } else if predicates
1594                .predicates
1595                .iter()
1596                .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1597            {
1598                // Avoid duplication of predicates that contain no parameters, for example.
1599                None
1600            } else {
1601                Some((instantiated_pred, sp))
1602            }
1603        })
1604        .map(|(pred, sp)| {
1605            // Convert each of those into an obligation. So if you have
1606            // something like `struct Foo<T: Copy = String>`, we would
1607            // take that predicate `T: Copy`, instantiated with `String: Copy`
1608            // (actually that happens in the previous `flat_map` call),
1609            // and then try to prove it (in this case, we'll fail).
1610            //
1611            // Note the subtle difference from how we handle `predicates`
1612            // below: there, we are not trying to prove those predicates
1613            // to be *true* but merely *well-formed*.
1614            let pred = wfcx.normalize(sp, None, pred);
1615            let cause = traits::ObligationCause::new(
1616                sp,
1617                wfcx.body_def_id,
1618                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1619            );
1620            Obligation::new(tcx, cause, wfcx.param_env, pred)
1621        });
1622
1623    let predicates = predicates.instantiate_identity(tcx);
1624
1625    let assoc_const_obligations: Vec<_> = predicates
1626        .predicates
1627        .iter()
1628        .copied()
1629        .zip(predicates.spans.iter().copied())
1630        .filter_map(|(clause, sp)| {
1631            let clause = clause.skip_norm_wip();
1632            let proj = clause.as_projection_clause()?;
1633            let pred_binder = proj
1634                .map_bound(|pred| {
1635                    pred.term.as_const().map(|ct| {
1636                        let assoc_const_ty = tcx
1637                            .type_of(pred.projection_term.def_id())
1638                            .instantiate(tcx, pred.projection_term.args)
1639                            .skip_norm_wip();
1640                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1641                    })
1642                })
1643                .transpose();
1644            pred_binder.map(|pred_binder| {
1645                let cause = traits::ObligationCause::new(
1646                    sp,
1647                    wfcx.body_def_id,
1648                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1649                );
1650                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1651            })
1652        })
1653        .collect();
1654
1655    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1656    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1657        traits::wf::clause_obligations(
1658            infcx,
1659            wfcx.param_env,
1660            wfcx.body_def_id,
1661            p.skip_norm_wip(),
1662            sp,
1663        )
1664    });
1665    let obligations: Vec<_> =
1666        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1667    wfcx.register_obligations(obligations);
1668}
1669
1670#[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(1670u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["sig", "def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            let mut sig =
                tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
            let arg_span =
                |idx|
                    hir_decl.inputs.get(idx).map_or(hir_decl.output.span(),
                        |arg: &hir::Ty<'_>| arg.span);
            sig.inputs_and_output =
                tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx,
                                ty)|
                            {
                                wfcx.deeply_normalize(arg_span(idx),
                                    Some(WellFormedLoc::Param {
                                            function: def_id,
                                            param_idx: idx,
                                        }), Unnormalized::new_wip(ty))
                            }));
            for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
                wfcx.register_wf_obligation(arg_span(idx),
                    Some(WellFormedLoc::Param {
                            function: def_id,
                            param_idx: idx,
                        }), ty.into());
            }
            check_where_clauses(wfcx, def_id);
            if sig.abi() == ExternAbi::RustCall {
                let span = tcx.def_span(def_id);
                let has_implicit_self =
                    hir_decl.implicit_self() != hir::ImplicitSelfKind::None;
                let mut inputs =
                    sig.inputs().iter().skip(if has_implicit_self {
                            1
                        } else { 0 });
                if let Some(ty) = inputs.next() {
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(hir::LangItem::Tuple, span));
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(hir::LangItem::Sized, span));
                } else {
                    tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
                            |input| input.span),
                        "functions with the \"rust-call\" ABI must take a single non-self tuple argument");
                }
                if inputs.next().is_some() {
                    tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
                            |input| input.span),
                        "functions with the \"rust-call\" ABI must take a single non-self tuple argument");
                }
            }
            if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
                let span =
                    match hir_decl.output {
                        hir::FnRetTy::Return(ty) => ty.span,
                        hir::FnRetTy::DefaultReturn(_) => body.value.span,
                    };
                wfcx.register_bound(ObligationCause::new(span, def_id,
                        ObligationCauseCode::SizedReturnType), wfcx.param_env,
                    sig.output(), tcx.require_lang_item(LangItem::Sized, span));
            }
        }
    }
}#[instrument(level = "debug", skip(wfcx, hir_decl))]
1671fn check_fn_or_method<'tcx>(
1672    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1673    sig: ty::PolyFnSig<'tcx>,
1674    hir_decl: &hir::FnDecl<'_>,
1675    def_id: LocalDefId,
1676) {
1677    let tcx = wfcx.tcx();
1678    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1679
1680    // Normalize the input and output types one at a time, using a different
1681    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1682    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1683    // for each type, preventing the HIR wf check from generating
1684    // a nice error message.
1685    let arg_span =
1686        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1687
1688    sig.inputs_and_output =
1689        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1690            wfcx.deeply_normalize(
1691                arg_span(idx),
1692                Some(WellFormedLoc::Param {
1693                    function: def_id,
1694                    // Note that the `param_idx` of the output type is
1695                    // one greater than the index of the last input type.
1696                    param_idx: idx,
1697                }),
1698                Unnormalized::new_wip(ty),
1699            )
1700        }));
1701
1702    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1703        wfcx.register_wf_obligation(
1704            arg_span(idx),
1705            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1706            ty.into(),
1707        );
1708    }
1709
1710    check_where_clauses(wfcx, def_id);
1711
1712    if sig.abi() == ExternAbi::RustCall {
1713        let span = tcx.def_span(def_id);
1714        let has_implicit_self = hir_decl.implicit_self() != hir::ImplicitSelfKind::None;
1715        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1716        // Check that the argument is a tuple and is sized
1717        if let Some(ty) = inputs.next() {
1718            wfcx.register_bound(
1719                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1720                wfcx.param_env,
1721                *ty,
1722                tcx.require_lang_item(hir::LangItem::Tuple, span),
1723            );
1724            wfcx.register_bound(
1725                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1726                wfcx.param_env,
1727                *ty,
1728                tcx.require_lang_item(hir::LangItem::Sized, span),
1729            );
1730        } else {
1731            tcx.dcx().span_err(
1732                hir_decl.inputs.last().map_or(span, |input| input.span),
1733                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1734            );
1735        }
1736        // No more inputs other than the `self` type and the tuple type
1737        if inputs.next().is_some() {
1738            tcx.dcx().span_err(
1739                hir_decl.inputs.last().map_or(span, |input| input.span),
1740                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1741            );
1742        }
1743    }
1744
1745    // If the function has a body, additionally require that the return type is sized.
1746    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1747        let span = match hir_decl.output {
1748            hir::FnRetTy::Return(ty) => ty.span,
1749            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1750        };
1751
1752        wfcx.register_bound(
1753            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1754            wfcx.param_env,
1755            sig.output(),
1756            tcx.require_lang_item(LangItem::Sized, span),
1757        );
1758    }
1759}
1760
1761/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1762#[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)]
1763enum ArbitrarySelfTypesLevel {
1764    Basic,        // just arbitrary_self_types
1765    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1766}
1767
1768#[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(1768u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["fn_sig", "method",
                                                    "self_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            if !method.is_method() { return Ok(()); }
            let span = fn_sig.decl.inputs[0].span;
            let loc =
                Some(WellFormedLoc::Param {
                        function: method.def_id.expect_local(),
                        param_idx: 0,
                    });
            let sig =
                tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
            let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
            let sig =
                wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1788",
                                    "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(1788u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("check_method_receiver: sig={0:?}",
                                                                sig) as &dyn Value))])
                        });
                } else { ; }
            };
            let self_ty =
                wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
            let receiver_ty = sig.inputs()[0];
            let receiver_ty =
                wfcx.normalize(DUMMY_SP, loc,
                    Unnormalized::new_wip(receiver_ty));
            receiver_ty.error_reported()?;
            let arbitrary_self_types_level =
                if tcx.features().arbitrary_self_types_pointers() {
                    Some(ArbitrarySelfTypesLevel::WithPointers)
                } else if tcx.features().arbitrary_self_types() {
                    Some(ArbitrarySelfTypesLevel::Basic)
                } else { None };
            let generics = tcx.generics_of(method.def_id);
            let receiver_validity =
                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                    arbitrary_self_types_level, generics);
            if let Err(receiver_validity_err) = receiver_validity {
                return Err(match arbitrary_self_types_level {
                            None if
                                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                                        Some(ArbitrarySelfTypesLevel::Basic), generics).is_ok() => {
                                feature_err(&tcx.sess, sym::arbitrary_self_types, span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types` feature",
                                                            receiver_ty))
                                                })).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
                            }
                            None | Some(ArbitrarySelfTypesLevel::Basic) if
                                receiver_is_valid(wfcx, span, receiver_ty, self_ty,
                                        Some(ArbitrarySelfTypesLevel::WithPointers),
                                        generics).is_ok() => {
                                feature_err(&tcx.sess, sym::arbitrary_self_types_pointers,
                                            span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types_pointers` feature",
                                                            receiver_ty))
                                                })).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
                            }
                            _ => {
                                match receiver_validity_err {
                                    ReceiverValidityError::DoesNotDeref if
                                        arbitrary_self_types_level.is_some() => {
                                        let hint =
                                            match receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def().and_then(|adt_def|
                                                        tcx.get_diagnostic_name(adt_def.did())) {
                                                Some(sym::RcWeak | sym::ArcWeak) =>
                                                    Some(InvalidReceiverTyHint::Weak),
                                                Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
                                                _ => None,
                                            };
                                        tcx.dcx().emit_err(errors::InvalidReceiverTy {
                                                span,
                                                receiver_ty,
                                                hint,
                                            })
                                    }
                                    ReceiverValidityError::DoesNotDeref => {
                                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
                                                span,
                                                receiver_ty,
                                            })
                                    }
                                    ReceiverValidityError::MethodGenericParamUsed => {
                                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy {
                                                span,
                                                receiver_ty,
                                            })
                                    }
                                }
                            }
                        });
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1769fn check_method_receiver<'tcx>(
1770    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1771    fn_sig: &hir::FnSig<'_>,
1772    method: ty::AssocItem,
1773    self_ty: Ty<'tcx>,
1774) -> Result<(), ErrorGuaranteed> {
1775    let tcx = wfcx.tcx();
1776
1777    if !method.is_method() {
1778        return Ok(());
1779    }
1780
1781    let span = fn_sig.decl.inputs[0].span;
1782    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1783
1784    let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1785    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1786    let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1787
1788    debug!("check_method_receiver: sig={:?}", sig);
1789
1790    let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1791
1792    let receiver_ty = sig.inputs()[0];
1793    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1794
1795    // If the receiver already has errors reported, consider it valid to avoid
1796    // unnecessary errors (#58712).
1797    receiver_ty.error_reported()?;
1798
1799    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1800        Some(ArbitrarySelfTypesLevel::WithPointers)
1801    } else if tcx.features().arbitrary_self_types() {
1802        Some(ArbitrarySelfTypesLevel::Basic)
1803    } else {
1804        None
1805    };
1806    let generics = tcx.generics_of(method.def_id);
1807
1808    let receiver_validity =
1809        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1810    if let Err(receiver_validity_err) = receiver_validity {
1811        return Err(match arbitrary_self_types_level {
1812            // Wherever possible, emit a message advising folks that the features
1813            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1814            // have helped.
1815            None if receiver_is_valid(
1816                wfcx,
1817                span,
1818                receiver_ty,
1819                self_ty,
1820                Some(ArbitrarySelfTypesLevel::Basic),
1821                generics,
1822            )
1823            .is_ok() =>
1824            {
1825                // Report error; would have worked with `arbitrary_self_types`.
1826                feature_err(
1827                    &tcx.sess,
1828                    sym::arbitrary_self_types,
1829                    span,
1830                    format!(
1831                        "`{receiver_ty}` cannot be used as the type of `self` without \
1832                            the `arbitrary_self_types` feature",
1833                    ),
1834                )
1835                .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>`"))
1836                .emit()
1837            }
1838            None | Some(ArbitrarySelfTypesLevel::Basic)
1839                if receiver_is_valid(
1840                    wfcx,
1841                    span,
1842                    receiver_ty,
1843                    self_ty,
1844                    Some(ArbitrarySelfTypesLevel::WithPointers),
1845                    generics,
1846                )
1847                .is_ok() =>
1848            {
1849                // Report error; would have worked with `arbitrary_self_types_pointers`.
1850                feature_err(
1851                    &tcx.sess,
1852                    sym::arbitrary_self_types_pointers,
1853                    span,
1854                    format!(
1855                        "`{receiver_ty}` cannot be used as the type of `self` without \
1856                            the `arbitrary_self_types_pointers` feature",
1857                    ),
1858                )
1859                .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>`"))
1860                .emit()
1861            }
1862            _ =>
1863            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1864            {
1865                match receiver_validity_err {
1866                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1867                        let hint = match receiver_ty
1868                            .builtin_deref(false)
1869                            .unwrap_or(receiver_ty)
1870                            .ty_adt_def()
1871                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1872                        {
1873                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1874                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1875                            _ => None,
1876                        };
1877
1878                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1879                    }
1880                    ReceiverValidityError::DoesNotDeref => {
1881                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1882                            span,
1883                            receiver_ty,
1884                        })
1885                    }
1886                    ReceiverValidityError::MethodGenericParamUsed => {
1887                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1888                    }
1889                }
1890            }
1891        });
1892    }
1893    Ok(())
1894}
1895
1896/// Error cases which may be returned from `receiver_is_valid`. These error
1897/// cases are generated in this function as they may be unearthed as we explore
1898/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1899enum ReceiverValidityError {
1900    /// The self type does not get to the receiver type by following the
1901    /// autoderef chain.
1902    DoesNotDeref,
1903    /// A type was found which is a method type parameter, and that's not allowed.
1904    MethodGenericParamUsed,
1905}
1906
1907/// Confirms that a type is not a type parameter referring to one of the
1908/// method's type params.
1909fn confirm_type_is_not_a_method_generic_param(
1910    ty: Ty<'_>,
1911    method_generics: &ty::Generics,
1912) -> Result<(), ReceiverValidityError> {
1913    if let ty::Param(param) = ty.kind() {
1914        if (param.index as usize) >= method_generics.parent_count {
1915            return Err(ReceiverValidityError::MethodGenericParamUsed);
1916        }
1917    }
1918    Ok(())
1919}
1920
1921/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1922/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1923/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1924/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1925/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1926///
1927/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1928/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1929/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1930fn receiver_is_valid<'tcx>(
1931    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1932    span: Span,
1933    receiver_ty: Ty<'tcx>,
1934    self_ty: Ty<'tcx>,
1935    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1936    method_generics: &ty::Generics,
1937) -> Result<(), ReceiverValidityError> {
1938    let infcx = wfcx.infcx;
1939    let tcx = wfcx.tcx();
1940    let cause =
1941        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1942
1943    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1944    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1945        let ocx = ObligationCtxt::new(wfcx.infcx);
1946        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1947        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1948            Ok(())
1949        } else {
1950            Err(NoSolution)
1951        }
1952    }) {
1953        return Ok(());
1954    }
1955
1956    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1957
1958    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1959
1960    // The `arbitrary_self_types` feature allows custom smart pointer
1961    // types to be method receivers, as identified by following the Receiver<Target=T>
1962    // chain.
1963    if arbitrary_self_types_enabled.is_some() {
1964        autoderef = autoderef.use_receiver_trait();
1965    }
1966
1967    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1968    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1969        autoderef = autoderef.include_raw_pointers();
1970    }
1971
1972    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1973    while let Some((potential_self_ty, _)) = autoderef.next() {
1974        {
    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:1974",
                        "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(1974u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
                                                    potential_self_ty, self_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
1975            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1976            potential_self_ty, self_ty
1977        );
1978
1979        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1980
1981        // Check if the self type unifies. If it does, then commit the result
1982        // since it may have region side-effects.
1983        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1984            let ocx = ObligationCtxt::new(wfcx.infcx);
1985            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1986            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1987                Ok(())
1988            } else {
1989                Err(NoSolution)
1990            }
1991        }) {
1992            wfcx.register_obligations(autoderef.into_obligations());
1993            return Ok(());
1994        }
1995
1996        // Without `feature(arbitrary_self_types)`, we require that each step in the
1997        // deref chain implement `LegacyReceiver`.
1998        if arbitrary_self_types_enabled.is_none() {
1999            let legacy_receiver_trait_def_id =
2000                tcx.require_lang_item(LangItem::LegacyReceiver, span);
2001            if !legacy_receiver_is_implemented(
2002                wfcx,
2003                legacy_receiver_trait_def_id,
2004                cause.clone(),
2005                potential_self_ty,
2006            ) {
2007                // We cannot proceed.
2008                break;
2009            }
2010
2011            // Register the bound, in case it has any region side-effects.
2012            wfcx.register_bound(
2013                cause.clone(),
2014                wfcx.param_env,
2015                potential_self_ty,
2016                legacy_receiver_trait_def_id,
2017            );
2018        }
2019    }
2020
2021    {
    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:2021",
                        "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(2021u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
                                                    receiver_ty, self_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
2022    Err(ReceiverValidityError::DoesNotDeref)
2023}
2024
2025fn legacy_receiver_is_implemented<'tcx>(
2026    wfcx: &WfCheckingCtxt<'_, 'tcx>,
2027    legacy_receiver_trait_def_id: DefId,
2028    cause: ObligationCause<'tcx>,
2029    receiver_ty: Ty<'tcx>,
2030) -> bool {
2031    let tcx = wfcx.tcx();
2032    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2033
2034    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2035
2036    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2037        true
2038    } else {
2039        {
    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:2039",
                        "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(2039u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
                                                    receiver_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
2040            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2041            receiver_ty
2042        );
2043        false
2044    }
2045}
2046
2047pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2048    match tcx.def_kind(def_id) {
2049        DefKind::Enum | DefKind::Struct | DefKind::Union => {
2050            // Ok
2051        }
2052        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:?}"),
2053    }
2054
2055    let ty_predicates = tcx.predicates_of(def_id);
2056    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);
2057    let variances = tcx.variances_of(def_id);
2058
2059    let mut constrained_parameters: FxHashSet<_> = variances
2060        .iter()
2061        .enumerate()
2062        .filter(|&(_, &variance)| variance != ty::Bivariant)
2063        .map(|(index, _)| Parameter(index as u32))
2064        .collect();
2065
2066    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2067
2068    // Lazily calculated because it is only needed in case of an error.
2069    let explicitly_bounded_params = LazyCell::new(|| {
2070        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2071        tcx.hir_node_by_def_id(def_id)
2072            .generics()
2073            .unwrap()
2074            .predicates
2075            .iter()
2076            .filter_map(|predicate| match predicate.kind {
2077                hir::WherePredicateKind::BoundPredicate(predicate) => {
2078                    match icx.lower_ty(predicate.bounded_ty).kind() {
2079                        ty::Param(data) => Some(Parameter(data.index)),
2080                        _ => None,
2081                    }
2082                }
2083                _ => None,
2084            })
2085            .collect::<FxHashSet<_>>()
2086    });
2087
2088    for (index, _) in variances.iter().enumerate() {
2089        let parameter = Parameter(index as u32);
2090
2091        if constrained_parameters.contains(&parameter) {
2092            continue;
2093        }
2094
2095        let node = tcx.hir_node_by_def_id(def_id);
2096        let item = node.expect_item();
2097        let hir_generics = node.generics().unwrap();
2098        let hir_param = &hir_generics.params[index];
2099
2100        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2101
2102        if ty_param.def_id != hir_param.def_id.into() {
2103            // Valid programs always have lifetimes before types in the generic parameter list.
2104            // ty_generics are normalized to be in this required order, and variances are built
2105            // from ty generics, not from hir generics. but we need hir generics to get
2106            // a span out.
2107            //
2108            // If they aren't in the same order, then the user has written invalid code, and already
2109            // got an error about it (or I'm wrong about this).
2110            tcx.dcx().span_delayed_bug(
2111                hir_param.span,
2112                "hir generics and ty generics in different order",
2113            );
2114            continue;
2115        }
2116
2117        // Look for `ErrorGuaranteed` deeply within this type.
2118        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2119            .type_of(def_id)
2120            .instantiate_identity()
2121            .skip_norm_wip()
2122            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2123        {
2124            continue;
2125        }
2126
2127        match hir_param.name {
2128            hir::ParamName::Error(_) => {
2129                // Don't report a bivariance error for a lifetime that isn't
2130                // even valid to name.
2131            }
2132            _ => {
2133                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2134                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2135            }
2136        }
2137    }
2138}
2139
2140/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2141struct HasErrorDeep<'tcx> {
2142    tcx: TyCtxt<'tcx>,
2143    seen: FxHashSet<DefId>,
2144}
2145impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2146    type Result = ControlFlow<ErrorGuaranteed>;
2147
2148    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2149        match *ty.kind() {
2150            ty::Adt(def, _) => {
2151                if self.seen.insert(def.did()) {
2152                    for field in def.all_fields() {
2153                        self.tcx
2154                            .type_of(field.did)
2155                            .instantiate_identity()
2156                            .skip_norm_wip()
2157                            .visit_with(self)?;
2158                    }
2159                }
2160            }
2161            ty::Error(guar) => return ControlFlow::Break(guar),
2162            _ => {}
2163        }
2164        ty.super_visit_with(self)
2165    }
2166
2167    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2168        if let Err(guar) = r.error_reported() {
2169            ControlFlow::Break(guar)
2170        } else {
2171            ControlFlow::Continue(())
2172        }
2173    }
2174
2175    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2176        if let Err(guar) = c.error_reported() {
2177            ControlFlow::Break(guar)
2178        } else {
2179            ControlFlow::Continue(())
2180        }
2181    }
2182}
2183
2184fn report_bivariance<'tcx>(
2185    tcx: TyCtxt<'tcx>,
2186    param: &'tcx hir::GenericParam<'tcx>,
2187    has_explicit_bounds: bool,
2188    item: &'tcx hir::Item<'tcx>,
2189) -> ErrorGuaranteed {
2190    let param_name = param.name.ident();
2191
2192    let help = match item.kind {
2193        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2194            if let Some(def_id) = tcx.lang_items().phantom_data() {
2195                errors::UnusedGenericParameterHelp::Adt {
2196                    param_name,
2197                    phantom_data: tcx.def_path_str(def_id),
2198                }
2199            } else {
2200                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2201            }
2202        }
2203        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:?}"),
2204    };
2205
2206    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2207    intravisit::walk_item(
2208        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2209        item,
2210    );
2211
2212    if !usage_spans.is_empty() {
2213        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2214        // not actually looking into substitutions, just walking through fields / the "RHS".
2215        // We don't recurse into the hidden types of opaques or anything else fancy.
2216        let item_def_id = item.owner_id.to_def_id();
2217        let is_probably_cyclical =
2218            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2219                .visit_def(item_def_id)
2220                .is_break();
2221        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2222        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2223        // alias, and we should call those parameter usages recursive rather than just saying
2224        // they're unused...
2225        //
2226        // We currently report *all* of the parameter usages, since computing the exact
2227        // subset is very involved, and the fact we're mentioning recursion at all is
2228        // likely to guide the user in the right direction.
2229        if is_probably_cyclical {
2230            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2231                spans: usage_spans,
2232                param_span: param.span,
2233                param_name,
2234                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2235                help,
2236                note: (),
2237            });
2238        }
2239    }
2240
2241    let const_param_help =
2242        #[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);
2243
2244    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2245        span: param.span,
2246        param_name,
2247        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2248        usage_spans,
2249        help,
2250        const_param_help,
2251    });
2252    diag.code(E0392);
2253    if item.kind.recovered() {
2254        // Silence potentially redundant error, as the item had a parse error.
2255        diag.delay_as_bug()
2256    } else {
2257        diag.emit()
2258    }
2259}
2260
2261/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2262/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2263/// cyclical.
2264///
2265/// Notably, we don't consider substitutions here, so this may have false positives.
2266struct IsProbablyCyclical<'tcx> {
2267    tcx: TyCtxt<'tcx>,
2268    item_def_id: DefId,
2269    seen: FxHashSet<DefId>,
2270}
2271
2272impl<'tcx> IsProbablyCyclical<'tcx> {
2273    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2274        match self.tcx.def_kind(def_id) {
2275            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2276                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2277                    self.tcx
2278                        .type_of(field.did)
2279                        .instantiate_identity()
2280                        .skip_norm_wip()
2281                        .visit_with(self)
2282                })
2283            }
2284            _ => ControlFlow::Continue(()),
2285        }
2286    }
2287}
2288
2289impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2290    type Result = ControlFlow<(), ()>;
2291
2292    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2293        if let Some(adt_def) = ty.ty_adt_def() {
2294            if adt_def.did() == self.item_def_id {
2295                return ControlFlow::Break(());
2296            }
2297            if self.seen.insert(adt_def.did()) {
2298                self.visit_def(adt_def.did())?;
2299            }
2300        }
2301        ty.super_visit_with(self)
2302    }
2303}
2304
2305/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2306///
2307/// This is used to report places where the user has used parameters in a
2308/// non-variance-constraining way for better bivariance errors.
2309struct CollectUsageSpans<'a> {
2310    spans: &'a mut Vec<Span>,
2311    param_def_id: DefId,
2312}
2313
2314impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2315    type Result = ();
2316
2317    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2318        // Skip the generics. We only care about fields, not where clause/param bounds.
2319    }
2320
2321    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2322        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2323            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2324                && def_id == self.param_def_id
2325            {
2326                self.spans.push(t.span);
2327                return;
2328            } else if let Res::SelfTyAlias { .. } = qpath.res {
2329                self.spans.push(t.span);
2330                return;
2331            }
2332        }
2333        intravisit::walk_ty(self, t);
2334    }
2335}
2336
2337impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2338    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2339    /// aren't true.
2340    #[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(2340u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.ocx.infcx.tcx;
            let mut span = tcx.def_span(self.body_def_id);
            let empty_env = ty::ParamEnv::empty();
            let predicates_with_span =
                tcx.predicates_of(self.body_def_id).predicates.iter().copied();
            let implied_obligations =
                traits::elaborate(tcx, predicates_with_span);
            for (pred, obligation_span) in implied_obligations {
                match pred.kind().skip_binder() {
                    ty::ClauseKind::WellFormed(..) |
                        ty::ClauseKind::UnstableFeature(..) => continue,
                    _ => {}
                }
                if pred.is_global() &&
                        !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
                    let pred =
                        self.normalize(span, None, Unnormalized::new_wip(pred));
                    let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
                    if let Some(hir::Generics { predicates, .. }) =
                            hir_node.generics() {
                        span =
                            predicates.iter().find(|pred|
                                            pred.span.contains(obligation_span)).map(|pred|
                                        pred.span).unwrap_or(obligation_span);
                    }
                    let obligation =
                        Obligation::new(tcx,
                            traits::ObligationCause::new(span, self.body_def_id,
                                ObligationCauseCode::TrivialBound), empty_env, pred);
                    self.ocx.register_obligation(obligation);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2341    fn check_false_global_bounds(&mut self) {
2342        let tcx = self.ocx.infcx.tcx;
2343        let mut span = tcx.def_span(self.body_def_id);
2344        let empty_env = ty::ParamEnv::empty();
2345
2346        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2347        // Check elaborated bounds.
2348        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2349
2350        for (pred, obligation_span) in implied_obligations {
2351            match pred.kind().skip_binder() {
2352                // We lower empty bounds like `Vec<dyn Copy>:` as
2353                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2354                // regular WF checking
2355                ty::ClauseKind::WellFormed(..)
2356                // Unstable feature goals cannot be proven in an empty environment so skip them
2357                | ty::ClauseKind::UnstableFeature(..) => continue,
2358                _ => {}
2359            }
2360
2361            // Match the existing behavior.
2362            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2363                let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2364
2365                // only use the span of the predicate clause (#90869)
2366                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2367                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2368                    span = predicates
2369                        .iter()
2370                        // There seems to be no better way to find out which predicate we are in
2371                        .find(|pred| pred.span.contains(obligation_span))
2372                        .map(|pred| pred.span)
2373                        .unwrap_or(obligation_span);
2374                }
2375
2376                let obligation = Obligation::new(
2377                    tcx,
2378                    traits::ObligationCause::new(
2379                        span,
2380                        self.body_def_id,
2381                        ObligationCauseCode::TrivialBound,
2382                    ),
2383                    empty_env,
2384                    pred,
2385                );
2386                self.ocx.register_obligation(obligation);
2387            }
2388        }
2389    }
2390}
2391
2392pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2393    let items = tcx.hir_crate_items(());
2394    let res =
2395        items
2396            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2397            .and(
2398                items.par_impl_items(|item| {
2399                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2400                }),
2401            )
2402            .and(items.par_trait_items(|item| {
2403                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2404            }))
2405            .and(items.par_foreign_items(|item| {
2406                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2407            }))
2408            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2409            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2410
2411    super::entry::check_for_entry_fn(tcx)?;
2412
2413    res
2414}
2415
2416fn lint_redundant_lifetimes<'tcx>(
2417    tcx: TyCtxt<'tcx>,
2418    owner_id: LocalDefId,
2419    outlives_env: &OutlivesEnvironment<'tcx>,
2420) {
2421    let def_kind = tcx.def_kind(owner_id);
2422    match def_kind {
2423        DefKind::Struct
2424        | DefKind::Union
2425        | DefKind::Enum
2426        | DefKind::Trait
2427        | DefKind::TraitAlias
2428        | DefKind::Fn
2429        | DefKind::Const { .. }
2430        | DefKind::Impl { of_trait: _ } => {
2431            // Proceed
2432        }
2433        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2434            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2435                // Don't check for redundant lifetimes for associated items of trait
2436                // implementations, since the signature is required to be compatible
2437                // with the trait, even if the implementation implies some lifetimes
2438                // are redundant.
2439                return;
2440            }
2441        }
2442        DefKind::Mod
2443        | DefKind::Variant
2444        | DefKind::TyAlias
2445        | DefKind::ForeignTy
2446        | DefKind::TyParam
2447        | DefKind::ConstParam
2448        | DefKind::Static { .. }
2449        | DefKind::Ctor(_, _)
2450        | DefKind::Macro(_)
2451        | DefKind::ExternCrate
2452        | DefKind::Use
2453        | DefKind::ForeignMod
2454        | DefKind::AnonConst
2455        | DefKind::InlineConst
2456        | DefKind::OpaqueTy
2457        | DefKind::Field
2458        | DefKind::LifetimeParam
2459        | DefKind::GlobalAsm
2460        | DefKind::Closure
2461        | DefKind::SyntheticCoroutineBody => return,
2462    }
2463
2464    // The ordering of this lifetime map is a bit subtle.
2465    //
2466    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2467    // where we can prove that `'candidate = 'victim`.
2468    //
2469    // `'static` must come first in this list because we can never replace `'static` with
2470    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2471    // suggest replacing `'a` with `'static`.
2472    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];
2473    lifetimes.extend(
2474        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2475    );
2476    // If we are in a function, add its late-bound lifetimes too.
2477    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2478        for (idx, var) in tcx
2479            .fn_sig(owner_id)
2480            .instantiate_identity()
2481            .skip_norm_wip()
2482            .bound_vars()
2483            .iter()
2484            .enumerate()
2485        {
2486            let ty::BoundVariableKind::Region(kind) = var else { continue };
2487            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2488            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2489        }
2490    }
2491    lifetimes.retain(|candidate| candidate.is_named(tcx));
2492
2493    // Keep track of lifetimes which have already been replaced with other lifetimes.
2494    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2495    // both `'a` and `'b`.
2496    let mut shadowed = FxHashSet::default();
2497
2498    for (idx, &candidate) in lifetimes.iter().enumerate() {
2499        // Don't suggest removing a lifetime twice. We only need to check this
2500        // here and not up in the `victim` loop because equality is transitive,
2501        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2502        // A's victim loop.
2503        if shadowed.contains(&candidate) {
2504            continue;
2505        }
2506
2507        for &victim in &lifetimes[(idx + 1)..] {
2508            // All region parameters should have a `DefId` available as:
2509            // - Late-bound parameters should be of the`BrNamed` variety,
2510            // since we get these signatures straight from `hir_lowering`.
2511            // - Early-bound parameters unconditionally have a `DefId` available.
2512            //
2513            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2514            // can't really suggest to remove them.
2515            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2516                continue;
2517            };
2518
2519            // Do not rename lifetimes not local to this item since they'll overlap
2520            // with the lint running on the parent. We still want to consider parent
2521            // lifetimes which make child lifetimes redundant, otherwise we would
2522            // have truncated the `identity_for_item` args above.
2523            if tcx.parent(def_id) != owner_id.to_def_id() {
2524                continue;
2525            }
2526
2527            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2528            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2529                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2530            {
2531                shadowed.insert(victim);
2532                tcx.emit_node_span_lint(
2533                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2534                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2535                    tcx.def_span(def_id),
2536                    RedundantLifetimeArgsLint { candidate, victim },
2537                );
2538            }
2539        }
2540    }
2541}
2542
2543#[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)]
2544#[diag("unnecessary lifetime parameter `{$victim}`")]
2545#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2546struct RedundantLifetimeArgsLint<'tcx> {
2547    /// The lifetime we have found to be redundant.
2548    victim: ty::Region<'tcx>,
2549    // The lifetime we can replace the victim with.
2550    candidate: ty::Region<'tcx>,
2551}