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::diagnostics;
48use crate::diagnostics::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            diagnostics::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            diagnostics::SupertraitItemShadowee::Several {
830                traits: traits.into(),
831                spans: spans.into(),
832            }
833        };
834
835        tcx.emit_node_span_lint(
836            SHADOWING_SUPERTRAIT_ITEMS,
837            tcx.local_def_id_to_hir_id(trait_item_def_id),
838            tcx.def_span(trait_item_def_id),
839            diagnostics::SupertraitItemShadowing {
840                item: item_name,
841                subtrait: tcx.item_name(trait_def_id.to_def_id()),
842                shadowee,
843            },
844        );
845    }
846}
847
848fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
849    match param.kind {
850        // We currently only check wf of const params here.
851        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
852
853        // Const parameters are well formed if their type is structural match.
854        ty::GenericParamDefKind::Const { .. } => {
855            let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
856            let span = tcx.def_span(param.def_id);
857            let def_id = param.def_id.expect_local();
858
859            if tcx.features().const_param_ty_unchecked() {
860                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
861                    wfcx.register_wf_obligation(span, None, ty.into());
862                    Ok(())
863                })
864            } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
865                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
866                    wfcx.register_bound(
867                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
868                        wfcx.param_env,
869                        ty,
870                        tcx.require_lang_item(LangItem::ConstParamTy, span),
871                    );
872                    Ok(())
873                })
874            } else {
875                let span = || {
876                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
877                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
878                    else {
879                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
880                    };
881                    span
882                };
883                let mut diag = match ty.kind() {
884                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
885                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
886                        span(),
887                        "using function pointers as const generic parameters is forbidden",
888                    ),
889                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
890                        span(),
891                        "using raw pointers as const generic parameters is forbidden",
892                    ),
893                    _ => {
894                        // Avoid showing "{type error}" to users. See #118179.
895                        ty.error_reported()?;
896
897                        tcx.dcx().struct_span_err(
898                            span(),
899                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
                ty))
    })format!(
900                                "`{ty}` is forbidden as the type of a const generic parameter",
901                            ),
902                        )
903                    }
904                };
905
906                diag.note("the only supported types are integers, `bool`, and `char`");
907
908                let cause = ObligationCause::misc(span(), def_id);
909                let adt_const_params_feature_string =
910                    " more complex and user defined types".to_string();
911                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
912                    tcx,
913                    tcx.param_env(param.def_id),
914                    ty,
915                    cause,
916                ) {
917                    // Can never implement `ConstParamTy`, don't suggest anything.
918                    Err(
919                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
920                        | ConstParamTyImplementationError::NonExhaustive(..)
921                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
922                    ) => None,
923                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
924                        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![
925                            (adt_const_params_feature_string, sym::min_adt_const_params),
926                            (
927                                " references to implement the `ConstParamTy` trait".into(),
928                                sym::unsized_const_params,
929                            ),
930                        ])
931                    }
932                    // May be able to implement `ConstParamTy`. Only emit the feature help
933                    // if the type is local, since the user may be able to fix the local type.
934                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
935                        fn ty_is_local(ty: Ty<'_>) -> bool {
936                            match ty.kind() {
937                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
938                                // Arrays and slices use the inner type's `ConstParamTy`.
939                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
940                                // `&` references use the inner type's `ConstParamTy`.
941                                // `&mut` are not supported.
942                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
943                                // Say that a tuple is local if any of its components are local.
944                                // This is not strictly correct, but it's likely that the user can fix the local component.
945                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
946                                _ => false,
947                            }
948                        }
949
950                        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![(
951                            adt_const_params_feature_string,
952                            sym::min_adt_const_params,
953                        )])
954                    }
955                    // Implements `ConstParamTy`, suggest adding the feature to enable.
956                    Ok(..) => {
957                        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)])
958                    }
959                };
960                if let Some(features) = may_suggest_feature {
961                    tcx.disabled_nightly_features(&mut diag, features);
962                }
963
964                Err(diag.emit())
965            }
966        }
967    }
968}
969
970#[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(970u32),
                                    ::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))]
971pub(crate) fn check_associated_item(
972    tcx: TyCtxt<'_>,
973    def_id: LocalDefId,
974) -> Result<(), ErrorGuaranteed> {
975    let loc = Some(WellFormedLoc::Ty(def_id));
976    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
977        let item = tcx.associated_item(def_id);
978
979        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
980        // other `Foo` impls are incoherent.
981        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
982
983        let self_ty = match item.container {
984            ty::AssocContainer::Trait => tcx.types.self_param,
985            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
986                tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
987            }
988        };
989
990        let span = tcx.def_span(def_id);
991
992        match item.kind {
993            ty::AssocKind::Const { .. } => {
994                let ty = tcx.type_of(def_id).instantiate_identity();
995                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
996                wfcx.register_wf_obligation(span, loc, ty.into());
997
998                let has_value = item.defaultness(tcx).has_value();
999                if tcx.is_type_const(def_id) {
1000                    check_type_const(wfcx, def_id, ty, has_value)?;
1001                }
1002
1003                if has_value {
1004                    let code = ObligationCauseCode::SizedConstOrStatic;
1005                    wfcx.register_bound(
1006                        ObligationCause::new(span, def_id, code),
1007                        wfcx.param_env,
1008                        ty,
1009                        tcx.require_lang_item(LangItem::Sized, span),
1010                    );
1011                }
1012
1013                Ok(())
1014            }
1015            ty::AssocKind::Fn { .. } => {
1016                let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1017                let hir_sig =
1018                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1019                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1020                check_method_receiver(wfcx, hir_sig, item, self_ty)
1021            }
1022            ty::AssocKind::Type { .. } => {
1023                if let ty::AssocContainer::Trait = item.container {
1024                    check_associated_type_bounds(wfcx, item, span)
1025                }
1026                if item.defaultness(tcx).has_value() {
1027                    let ty = tcx.type_of(def_id).instantiate_identity();
1028                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1029                    wfcx.register_wf_obligation(span, loc, ty.into());
1030                }
1031                Ok(())
1032            }
1033        }
1034    })
1035}
1036
1037/// In a type definition, we check that to ensure that the types of the fields are well-formed.
1038pub(crate) fn check_type_defn<'tcx>(
1039    tcx: TyCtxt<'tcx>,
1040    item: LocalDefId,
1041    all_sized: bool,
1042) -> Result<(), ErrorGuaranteed> {
1043    tcx.ensure_ok().check_representability(item);
1044    let adt_def = tcx.adt_def(item);
1045
1046    enter_wf_checking_ctxt(tcx, item, |wfcx| {
1047        let variants = adt_def.variants();
1048        let packed = adt_def.repr().packed();
1049
1050        for variant in variants.iter() {
1051            // All field types must be well-formed.
1052            for field in &variant.fields {
1053                if let Some(def_id) = field.value
1054                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1055                {
1056                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1057                    // be refactored to check the instantiate-ability of the code better.
1058                    if let Some(def_id) = def_id.as_local()
1059                        && let DefKind::AnonConst = tcx.def_kind(def_id)
1060                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1061                        && let expr = &tcx.hir_body(anon.body).value
1062                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1063                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1064                    {
1065                        // Do not evaluate bare `const` params, as those would ICE and are only
1066                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1067                    } else {
1068                        // Evaluate the constant proactively, to emit an error if the constant has
1069                        // an unconditional error. We only do so if the const has no type params.
1070                        let _ = tcx.const_eval_poly(def_id);
1071                    }
1072                }
1073                let field_id = field.did.expect_local();
1074                let span = tcx.ty_span(field_id);
1075                let ty = wfcx.deeply_normalize(
1076                    span,
1077                    None,
1078                    tcx.type_of(field.did).instantiate_identity(),
1079                );
1080                wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1081
1082                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())
1083                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1084                {
1085                    // Scalable vectors can only be fields of structs if the type has a
1086                    // `rustc_scalable_vector` attribute w/out specifying an element count
1087                    tcx.dcx().span_err(
1088                        span,
1089                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1090                            "scalable vectors cannot be fields of a {}",
1091                            adt_def.variant_descr()
1092                        ),
1093                    );
1094                }
1095            }
1096
1097            // For DST, or when drop needs to copy things around, all
1098            // intermediate types must be sized.
1099            let needs_drop_copy = || {
1100                packed && {
1101                    let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1102                    let ty = tcx.erase_and_anonymize_regions(ty);
1103                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1104                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1105                }
1106            };
1107            // All fields (except for possibly the last) should be sized.
1108            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1109            let unsized_len = if all_sized { 0 } else { 1 };
1110            for (idx, field) in
1111                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1112            {
1113                let last = idx == variant.fields.len() - 1;
1114                let span = tcx.ty_span(field.did.expect_local());
1115                let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1116                wfcx.register_bound(
1117                    traits::ObligationCause::new(
1118                        span,
1119                        wfcx.body_def_id,
1120                        ObligationCauseCode::FieldSized {
1121                            adt_kind: adt_def.adt_kind(),
1122                            span,
1123                            last,
1124                        },
1125                    ),
1126                    wfcx.param_env,
1127                    ty,
1128                    tcx.require_lang_item(LangItem::Sized, span),
1129                );
1130            }
1131
1132            // Explicit `enum` discriminant values must const-evaluate successfully.
1133            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1134                match tcx.const_eval_poly(discr_def_id) {
1135                    Ok(_) => {}
1136                    Err(ErrorHandled::Reported(..)) => {}
1137                    Err(ErrorHandled::TooGeneric(sp)) => {
1138                        ::rustc_middle::util::bug::span_bug_fmt(sp,
    format_args!("enum variant discr was too generic to eval"))span_bug!(sp, "enum variant discr was too generic to eval")
1139                    }
1140                }
1141            }
1142        }
1143
1144        check_where_clauses(wfcx, item);
1145        Ok(())
1146    })
1147}
1148
1149#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_trait",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1149u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["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))]
1150pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1151    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1152        // `PointeeSized` is removed during lowering.
1153        return Ok(());
1154    }
1155
1156    let trait_def = tcx.trait_def(def_id);
1157    if trait_def.is_marker
1158        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1159    {
1160        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1161            struct_span_code_err!(
1162                tcx.dcx(),
1163                tcx.def_span(*associated_def_id),
1164                E0714,
1165                "marker traits cannot have associated items",
1166            )
1167            .emit();
1168        }
1169    }
1170
1171    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1172        check_where_clauses(wfcx, def_id);
1173        Ok(())
1174    });
1175
1176    res
1177}
1178
1179/// Checks all associated type defaults of trait `trait_def_id`.
1180///
1181/// Assuming the defaults are used, check that all predicates (bounds on the
1182/// assoc type and where clauses on the trait) hold.
1183fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1184    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1185
1186    {
    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:1186",
                        "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(1186u32),
                        ::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);
1187    let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1188        |(bound, bound_span)| {
1189            traits::wf::clause_obligations(
1190                wfcx.infcx,
1191                wfcx.param_env,
1192                wfcx.body_def_id,
1193                bound,
1194                bound_span,
1195            )
1196        },
1197    );
1198
1199    wfcx.register_obligations(wf_obligations);
1200}
1201
1202fn check_item_fn(
1203    tcx: TyCtxt<'_>,
1204    def_id: LocalDefId,
1205    decl: &hir::FnDecl<'_>,
1206) -> Result<(), ErrorGuaranteed> {
1207    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1208        check_eiis_fn(tcx, def_id);
1209
1210        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1211        check_fn_or_method(wfcx, sig, decl, def_id);
1212        Ok(())
1213    })
1214}
1215
1216fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1217    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1218    // that was used to mark the implementation. This is a two step process.
1219    for EiiImpl { resolution, span, .. } in
1220        {
    {
        '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()
1221    {
1222        let (foreign_item, name) = match resolution {
1223            EiiImplResolution::Macro(def_id) => {
1224                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1225                // signature that we'd like to compare the function we're currently checking with
1226                if let Some(foreign_item) =
1227                    {
    {
        '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)
1228                {
1229                    (foreign_item, tcx.item_name(*def_id))
1230                } else {
1231                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1232                    continue;
1233                }
1234            }
1235            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1236            EiiImplResolution::Error(_eg) => continue,
1237        };
1238
1239        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1240    }
1241}
1242
1243fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1244    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1245    // that was used to mark the implementation. This is a two step process.
1246    for EiiImpl { resolution, span, .. } in
1247        {
    {
        '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()
1248    {
1249        let (foreign_item, name) = match resolution {
1250            EiiImplResolution::Macro(def_id) => {
1251                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1252                // signature that we'd like to compare the function we're currently checking with
1253                if let Some(foreign_item) =
1254                    {
    {
        '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)
1255                {
1256                    (foreign_item, tcx.item_name(*def_id))
1257                } else {
1258                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1259                    continue;
1260                }
1261            }
1262            EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1263            EiiImplResolution::Error(_eg) => continue,
1264        };
1265
1266        let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1267    }
1268}
1269
1270#[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(1270u32),
                                    ::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))]
1271pub(crate) fn check_static_item<'tcx>(
1272    tcx: TyCtxt<'tcx>,
1273    item_id: LocalDefId,
1274    ty: Ty<'tcx>,
1275    should_check_for_sync: bool,
1276) -> Result<(), ErrorGuaranteed> {
1277    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1278        if should_check_for_sync {
1279            check_eiis_static(tcx, item_id, ty);
1280        }
1281
1282        let span = tcx.ty_span(item_id);
1283        let loc = Some(WellFormedLoc::Ty(item_id));
1284        let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1285
1286        let is_foreign_item = tcx.is_foreign_item(item_id);
1287        let is_structurally_foreign_item = || {
1288            let tail = tcx.struct_tail_raw(
1289                item_ty,
1290                &ObligationCause::dummy(),
1291                |ty| wfcx.deeply_normalize(span, loc, ty),
1292                || {},
1293            );
1294
1295            matches!(tail.kind(), ty::Foreign(_))
1296        };
1297        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1298
1299        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1300        if forbid_unsized {
1301            let span = tcx.def_span(item_id);
1302            wfcx.register_bound(
1303                traits::ObligationCause::new(
1304                    span,
1305                    wfcx.body_def_id,
1306                    ObligationCauseCode::SizedConstOrStatic,
1307                ),
1308                wfcx.param_env,
1309                item_ty,
1310                tcx.require_lang_item(LangItem::Sized, span),
1311            );
1312        }
1313
1314        // Ensure that the end result is `Sync` in a non-thread local `static`.
1315        let should_check_for_sync = should_check_for_sync
1316            && !is_foreign_item
1317            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1318            && !tcx.is_thread_local_static(item_id.to_def_id());
1319
1320        if should_check_for_sync {
1321            wfcx.register_bound(
1322                traits::ObligationCause::new(
1323                    span,
1324                    wfcx.body_def_id,
1325                    ObligationCauseCode::SharedStatic,
1326                ),
1327                wfcx.param_env,
1328                item_ty,
1329                tcx.require_lang_item(LangItem::Sync, span),
1330            );
1331        }
1332        Ok(())
1333    })
1334}
1335
1336#[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(1336u32),
                                    ::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))]
1337pub(super) fn check_type_const<'tcx>(
1338    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1339    def_id: LocalDefId,
1340    item_ty: Ty<'tcx>,
1341    has_value: bool,
1342) -> Result<(), ErrorGuaranteed> {
1343    let tcx = wfcx.tcx();
1344    let span = tcx.def_span(def_id);
1345
1346    if !tcx.features().const_param_ty_unchecked() {
1347        wfcx.register_bound(
1348            ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1349            wfcx.param_env,
1350            item_ty,
1351            tcx.require_lang_item(LangItem::ConstParamTy, span),
1352        );
1353    }
1354
1355    if has_value {
1356        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1357        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1358        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1359
1360        wfcx.register_obligation(Obligation::new(
1361            tcx,
1362            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1363            wfcx.param_env,
1364            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1365        ));
1366    }
1367    Ok(())
1368}
1369
1370#[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(1370u32),
                                    ::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:1442",
                                                        "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(1442u32),
                                                        ::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_))]
1371fn check_impl<'tcx>(
1372    tcx: TyCtxt<'tcx>,
1373    item: &'tcx hir::Item<'tcx>,
1374    impl_: &hir::Impl<'_>,
1375) -> Result<(), ErrorGuaranteed> {
1376    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1377        match impl_.of_trait {
1378            Some(of_trait) => {
1379                // `#[rustc_reservation_impl]` impls are not real impls and
1380                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1381                // won't hold).
1382                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1383                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1384                // case other `Foo` impls are incoherent.
1385                tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1386                let trait_span = of_trait.trait_ref.path.span;
1387                let trait_ref = wfcx.deeply_normalize(
1388                    trait_span,
1389                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1390                    trait_ref,
1391                );
1392                let trait_pred =
1393                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1394                let mut obligations = traits::wf::trait_obligations(
1395                    wfcx.infcx,
1396                    wfcx.param_env,
1397                    wfcx.body_def_id,
1398                    trait_pred,
1399                    trait_span,
1400                    item,
1401                );
1402                for obligation in &mut obligations {
1403                    if obligation.cause.span != trait_span {
1404                        // We already have a better span.
1405                        continue;
1406                    }
1407                    if let Some(pred) = obligation.predicate.as_trait_clause()
1408                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1409                    {
1410                        obligation.cause.span = impl_.self_ty.span;
1411                    }
1412                    if let Some(pred) = obligation.predicate.as_projection_clause()
1413                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1414                    {
1415                        obligation.cause.span = impl_.self_ty.span;
1416                    }
1417                }
1418
1419                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1420                if tcx.is_conditionally_const(item.owner_id.def_id) {
1421                    for (bound, _) in
1422                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1423                    {
1424                        let bound = wfcx.normalize(
1425                            item.span,
1426                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1427                            bound,
1428                        );
1429                        wfcx.register_obligation(Obligation::new(
1430                            tcx,
1431                            ObligationCause::new(
1432                                impl_.self_ty.span,
1433                                wfcx.body_def_id,
1434                                ObligationCauseCode::WellFormed(None),
1435                            ),
1436                            wfcx.param_env,
1437                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1438                        ))
1439                    }
1440                }
1441
1442                debug!(?obligations);
1443                wfcx.register_obligations(obligations);
1444            }
1445            None => {
1446                let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1447                let self_ty = wfcx.deeply_normalize(
1448                    item.span,
1449                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1450                    Unnormalized::new_wip(self_ty),
1451                );
1452                wfcx.register_wf_obligation(
1453                    impl_.self_ty.span,
1454                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1455                    self_ty.into(),
1456                );
1457            }
1458        }
1459
1460        check_where_clauses(wfcx, item.owner_id.def_id);
1461        Ok(())
1462    })
1463}
1464
1465/// Checks where-clauses and inline bounds that are declared on `def_id`.
1466#[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(1466u32),
                                    ::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 =
                                                                    pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
                                                                ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
                                                            })
                                                }).transpose();
                                pred_binder.map(|pred_binder|
                                        {
                                            let cause =
                                                traits::ObligationCause::new(sp, wfcx.body_def_id,
                                                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
                                            Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
                                        })
                            }).collect();
            match (&predicates.predicates.len(), &predicates.spans.len()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let wf_obligations =
                predicates.into_iter().flat_map(|(p, sp)|
                        {
                            traits::wf::clause_obligations(infcx, wfcx.param_env,
                                wfcx.body_def_id, p.skip_norm_wip(), sp)
                        });
            let obligations: Vec<_> =
                wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
            wfcx.register_obligations(obligations);
        }
    }
}#[instrument(level = "debug", skip(wfcx))]
1467pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1468    let infcx = wfcx.infcx;
1469    let tcx = wfcx.tcx();
1470
1471    let predicates = tcx.predicates_of(def_id.to_def_id());
1472    let generics = tcx.generics_of(def_id);
1473
1474    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1475    // For example, this forbids the declaration:
1476    //
1477    //     struct Foo<T = Vec<[u32]>> { .. }
1478    //
1479    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1480    for param in &generics.own_params {
1481        if let Some(default) = param
1482            .default_value(tcx)
1483            .map(ty::EarlyBinder::instantiate_identity)
1484            .map(Unnormalized::skip_norm_wip)
1485        {
1486            // Ignore dependent defaults -- that is, where the default of one type
1487            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1488            // be sure if it will error or not as user might always specify the other.
1489            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1490            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1491            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1492            if !default.has_param() {
1493                wfcx.register_wf_obligation(
1494                    tcx.def_span(param.def_id),
1495                    matches!(param.kind, GenericParamDefKind::Type { .. })
1496                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1497                    default.as_term().unwrap(),
1498                );
1499            } else {
1500                // If we've got a generic const parameter we still want to check its
1501                // type is correct in case both it and the param type are fully concrete.
1502                let GenericArgKind::Const(ct) = default.kind() else {
1503                    continue;
1504                };
1505
1506                let ct_ty = match ct.kind() {
1507                    ty::ConstKind::Infer(_)
1508                    | ty::ConstKind::Placeholder(_)
1509                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1510                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1511                    ty::ConstKind::Value(cv) => cv.ty,
1512                    ty::ConstKind::Unevaluated(uv) => uv.type_of(infcx.tcx).skip_norm_wip(),
1513                    ty::ConstKind::Param(param_ct) => {
1514                        param_ct.find_const_ty_from_env(wfcx.param_env)
1515                    }
1516                };
1517
1518                let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1519                if !ct_ty.has_param() && !param_ty.has_param() {
1520                    let cause = traits::ObligationCause::new(
1521                        tcx.def_span(param.def_id),
1522                        wfcx.body_def_id,
1523                        ObligationCauseCode::WellFormed(None),
1524                    );
1525                    wfcx.register_obligation(Obligation::new(
1526                        tcx,
1527                        cause,
1528                        wfcx.param_env,
1529                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1530                    ));
1531                }
1532            }
1533        }
1534    }
1535
1536    // Check that trait predicates are WF when params are instantiated with their defaults.
1537    // We don't want to overly constrain the predicates that may be written but we want to
1538    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1539    // Therefore we check if a predicate which contains a single type param
1540    // with a concrete default is WF with that default instantiated.
1541    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1542    //
1543    // First we build the defaulted generic parameters.
1544    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1545        if param.index >= generics.parent_count as u32
1546            // If the param has a default, ...
1547            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1548            // ... and it's not a dependent default, ...
1549            && !default.has_param()
1550        {
1551            // ... then instantiate it with the default.
1552            return default;
1553        }
1554        tcx.mk_param_from_def(param)
1555    });
1556
1557    // Now we build the instantiated predicates.
1558    let default_obligations = predicates
1559        .predicates
1560        .iter()
1561        .flat_map(|&(pred, sp)| {
1562            #[derive(Default)]
1563            struct CountParams {
1564                params: FxHashSet<u32>,
1565            }
1566            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1567                type Result = ControlFlow<()>;
1568                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1569                    if let ty::Param(param) = t.kind() {
1570                        self.params.insert(param.index);
1571                    }
1572                    t.super_visit_with(self)
1573                }
1574
1575                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1576                    ControlFlow::Break(())
1577                }
1578
1579                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1580                    if let ty::ConstKind::Param(param) = c.kind() {
1581                        self.params.insert(param.index);
1582                    }
1583                    c.super_visit_with(self)
1584                }
1585            }
1586            let mut param_count = CountParams::default();
1587            let has_region = pred.visit_with(&mut param_count).is_break();
1588            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1589            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1590            // or preds with multiple params.
1591            if instantiated_pred.skip_normalization().has_non_region_param()
1592                || param_count.params.len() > 1
1593                || has_region
1594            {
1595                None
1596            } else if predicates
1597                .predicates
1598                .iter()
1599                .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1600            {
1601                // Avoid duplication of predicates that contain no parameters, for example.
1602                None
1603            } else {
1604                Some((instantiated_pred, sp))
1605            }
1606        })
1607        .map(|(pred, sp)| {
1608            // Convert each of those into an obligation. So if you have
1609            // something like `struct Foo<T: Copy = String>`, we would
1610            // take that predicate `T: Copy`, instantiated with `String: Copy`
1611            // (actually that happens in the previous `flat_map` call),
1612            // and then try to prove it (in this case, we'll fail).
1613            //
1614            // Note the subtle difference from how we handle `predicates`
1615            // below: there, we are not trying to prove those predicates
1616            // to be *true* but merely *well-formed*.
1617            let pred = wfcx.normalize(sp, None, pred);
1618            let cause = traits::ObligationCause::new(
1619                sp,
1620                wfcx.body_def_id,
1621                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1622            );
1623            Obligation::new(tcx, cause, wfcx.param_env, pred)
1624        });
1625
1626    let predicates = predicates.instantiate_identity(tcx);
1627
1628    let assoc_const_obligations: Vec<_> = predicates
1629        .predicates
1630        .iter()
1631        .copied()
1632        .zip(predicates.spans.iter().copied())
1633        .filter_map(|(clause, sp)| {
1634            let clause = clause.skip_norm_wip();
1635            let proj = clause.as_projection_clause()?;
1636            let pred_binder = proj
1637                .map_bound(|pred| {
1638                    pred.term.as_const().map(|ct| {
1639                        let assoc_const_ty =
1640                            pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1641                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1642                    })
1643                })
1644                .transpose();
1645            pred_binder.map(|pred_binder| {
1646                let cause = traits::ObligationCause::new(
1647                    sp,
1648                    wfcx.body_def_id,
1649                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1650                );
1651                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1652            })
1653        })
1654        .collect();
1655
1656    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1657    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1658        traits::wf::clause_obligations(
1659            infcx,
1660            wfcx.param_env,
1661            wfcx.body_def_id,
1662            p.skip_norm_wip(),
1663            sp,
1664        )
1665    });
1666    let obligations: Vec<_> =
1667        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1668    wfcx.register_obligations(obligations);
1669}
1670
1671#[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(1671u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&["sig", "def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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