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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let loc = Some(WellFormedLoc::Ty(def_id));
            enter_wf_checking_ctxt(tcx, def_id,
                |wfcx|
                    {
                        let item = tcx.associated_item(def_id);
                        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
                        let self_ty =
                            match item.container {
                                ty::AssocContainer::Trait => tcx.types.self_param,
                                ty::AssocContainer::InherentImpl |
                                    ty::AssocContainer::TraitImpl(_) => {
                                    tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
                                }
                            };
                        let span = tcx.def_span(def_id);
                        match item.kind {
                            ty::AssocKind::Const { .. } => {
                                let ty = tcx.type_of(def_id).instantiate_identity();
                                let ty =
                                    wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
                                        ty);
                                wfcx.register_wf_obligation(span, loc, ty.into());
                                if item.defaultness(tcx).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));
                                }
                                check_const_item(wfcx, def_id, ty)
                            }
                            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))]
915pub(crate) fn check_associated_item(
916    tcx: TyCtxt<'_>,
917    def_id: LocalDefId,
918) -> Result<(), ErrorGuaranteed> {
919    let loc = Some(WellFormedLoc::Ty(def_id));
920    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
921        let item = tcx.associated_item(def_id);
922
923        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
924        // other `Foo` impls are incoherent.
925        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
926
927        let self_ty = match item.container {
928            ty::AssocContainer::Trait => tcx.types.self_param,
929            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
930                tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
931            }
932        };
933
934        let span = tcx.def_span(def_id);
935
936        match item.kind {
937            ty::AssocKind::Const { .. } => {
938                let ty = tcx.type_of(def_id).instantiate_identity();
939                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
940                wfcx.register_wf_obligation(span, loc, ty.into());
941
942                if item.defaultness(tcx).has_value() {
943                    let code = ObligationCauseCode::SizedConstOrStatic;
944                    wfcx.register_bound(
945                        ObligationCause::new(span, def_id, code),
946                        wfcx.param_env,
947                        ty,
948                        tcx.require_lang_item(LangItem::Sized, span),
949                    );
950                }
951
952                check_const_item(wfcx, def_id, ty)
953            }
954            ty::AssocKind::Fn { .. } => {
955                let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
956                let hir_sig =
957                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
958                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
959                check_method_receiver(wfcx, hir_sig, item, self_ty)
960            }
961            ty::AssocKind::Type { .. } => {
962                if let ty::AssocContainer::Trait = item.container {
963                    check_associated_type_bounds(wfcx, item, span)
964                }
965                if item.defaultness(tcx).has_value() {
966                    let ty = tcx.type_of(def_id).instantiate_identity();
967                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
968                    wfcx.register_wf_obligation(span, loc, ty.into());
969                }
970                Ok(())
971            }
972        }
973    })
974}
975
976/// In a type definition, we check that to ensure that the types of the fields are well-formed.
977pub(crate) fn check_type_defn<'tcx>(
978    tcx: TyCtxt<'tcx>,
979    item: LocalDefId,
980    all_sized: bool,
981) -> Result<(), ErrorGuaranteed> {
982    tcx.ensure_ok().check_representability(item);
983    let adt_def = tcx.adt_def(item);
984
985    enter_wf_checking_ctxt(tcx, item, |wfcx| {
986        let variants = adt_def.variants();
987        let packed = adt_def.repr().packed();
988
989        for variant in variants.iter() {
990            // All field types must be well-formed.
991            for field in &variant.fields {
992                if let Some(def_id) = field.value
993                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
994                {
995                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
996                    // be refactored to check the instantiate-ability of the code better.
997                    if let Some(def_id) = def_id.as_local()
998                        && let DefKind::AnonConst = tcx.def_kind(def_id)
999                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1000                        && let expr = &tcx.hir_body(anon.body).value
1001                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1002                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1003                    {
1004                        // Do not evaluate bare `const` params, as those would ICE and are only
1005                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1006                    } else {
1007                        // Evaluate the constant proactively, to emit an error if the constant has
1008                        // an unconditional error. We only do so if the const has no type params.
1009                        let _ = tcx.const_eval_poly(def_id);
1010                    }
1011                }
1012                let field_id = field.did.expect_local();
1013                let span = tcx.ty_span(field_id);
1014                let ty = wfcx.deeply_normalize(
1015                    span,
1016                    None,
1017                    tcx.type_of(field.did).instantiate_identity(),
1018                );
1019                wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1020
1021                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())
1022                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1023                {
1024                    // Scalable vectors can only be fields of structs if the type has a
1025                    // `rustc_scalable_vector` attribute w/out specifying an element count
1026                    tcx.dcx().span_err(
1027                        span,
1028                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1029                            "scalable vectors cannot be fields of a {}",
1030                            adt_def.variant_descr()
1031                        ),
1032                    );
1033                }
1034            }
1035
1036            // For DST, or when drop needs to copy things around, all
1037            // intermediate types must be sized.
1038            let needs_drop_copy = || {
1039                packed && {
1040                    let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1041                    let ty = tcx.erase_and_anonymize_regions(ty);
1042                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1043                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1044                }
1045            };
1046            // All fields (except for possibly the last) should be sized.
1047            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1048            let unsized_len = if all_sized { 0 } else { 1 };
1049            for (idx, field) in
1050                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1051            {
1052                let last = idx == variant.fields.len() - 1;
1053                let span = tcx.ty_span(field.did.expect_local());
1054                let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1055                wfcx.register_bound(
1056                    traits::ObligationCause::new(
1057                        span,
1058                        wfcx.body_def_id,
1059                        ObligationCauseCode::FieldSized {
1060                            adt_kind: adt_def.adt_kind(),
1061                            span,
1062                            last,
1063                        },
1064                    ),
1065                    wfcx.param_env,
1066                    ty,
1067                    tcx.require_lang_item(LangItem::Sized, span),
1068                );
1069            }
1070
1071            // Explicit `enum` discriminant values must const-evaluate successfully.
1072            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1073                match tcx.const_eval_poly(discr_def_id) {
1074                    Ok(_) => {}
1075                    Err(ErrorHandled::Reported(..)) => {}
1076                    Err(ErrorHandled::TooGeneric(sp)) => {
1077                        ::rustc_span::macros::bug_impl(Some(sp),
    format_args!("enum variant discr was too generic to eval"),
    Location::caller())span_bug!(sp, "enum variant discr was too generic to eval")
1078                    }
1079                }
1080            }
1081        }
1082
1083        check_where_clauses(wfcx, item);
1084        Ok(())
1085    })
1086}
1087
1088{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1088u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
                return Ok(());
            }
            let trait_def = tcx.trait_def(def_id);
            if trait_def.is_marker ||
                    #[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
                        {
                        TraitSpecializationKind::Marker => true,
                        _ => false,
                    } {
                for associated_def_id in &*tcx.associated_item_def_ids(def_id)
                    {
                    {
                            tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
                                        })).with_code(E0714)
                        }.emit();
                }
            }
            let res =
                enter_wf_checking_ctxt(tcx, def_id,
                    |wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
            res
        }
    }
}#[instrument(skip(tcx))]
1089pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1090    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1091        // `PointeeSized` is removed during lowering.
1092        return Ok(());
1093    }
1094
1095    let trait_def = tcx.trait_def(def_id);
1096    if trait_def.is_marker
1097        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1098    {
1099        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1100            struct_span_code_err!(
1101                tcx.dcx(),
1102                tcx.def_span(*associated_def_id),
1103                E0714,
1104                "marker traits cannot have associated items",
1105            )
1106            .emit();
1107        }
1108    }
1109
1110    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1111        check_where_clauses(wfcx, def_id);
1112        Ok(())
1113    });
1114
1115    res
1116}
1117
1118/// Checks all associated type defaults of trait `trait_def_id`.
1119///
1120/// Assuming the defaults are used, check that all predicates (bounds on the
1121/// assoc type and where clauses on the trait) hold.
1122fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1123    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1124
1125    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1125",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1125u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
                                                    bounds) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1126    let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1127        |(bound, bound_span)| {
1128            traits::wf::clause_obligations(
1129                wfcx.infcx,
1130                wfcx.param_env,
1131                wfcx.body_def_id,
1132                bound,
1133                bound_span,
1134            )
1135        },
1136    );
1137
1138    wfcx.register_obligations(wf_obligations);
1139}
1140
1141fn check_item_fn(
1142    tcx: TyCtxt<'_>,
1143    def_id: LocalDefId,
1144    decl: &hir::FnDecl<'_>,
1145) -> Result<(), ErrorGuaranteed> {
1146    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1147        check_eiis_fn(tcx, def_id);
1148
1149        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1150        check_fn_or_method(wfcx, sig, decl, def_id);
1151        Ok(())
1152    })
1153}
1154
1155fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1156    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1157    // that was used to mark the implementation. This is a two step process.
1158    if let Some(EiiImpl { resolution, span, .. }) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
                        break 'done Some(&**i);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1159        let (foreign_item, name) = match resolution {
1160            EiiImplResolution::Macro(def_id) => {
1161                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1162                // signature that we'd like to compare the function we're currently checking with
1163                if let Some(foreign_item) =
1164                    {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1165                {
1166                    (foreign_item, tcx.item_name(*def_id))
1167                } else {
1168                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1169                    return;
1170                }
1171            }
1172            EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1173            EiiImplResolution::Error(_eg) => return,
1174        };
1175
1176        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1177    }
1178}
1179
1180fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1181    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1182    // that was used to mark the implementation. This is a two step process.
1183    if let Some(EiiImpl { resolution, span, .. }) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
                        break 'done Some(&**i);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1184        let (foreign_item, name) = match resolution {
1185            EiiImplResolution::Macro(def_id) => {
1186                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1187                // signature that we'd like to compare the function we're currently checking with
1188                if let Some(foreign_item) =
1189                    {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1190                {
1191                    (foreign_item, tcx.item_name(*def_id))
1192                } else {
1193                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1194                    return;
1195                }
1196            }
1197            EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1198            EiiImplResolution::Error(_eg) => return,
1199        };
1200
1201        let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1202    }
1203}
1204
1205{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1205u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("should_check_for_sync")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("should_check_for_sync");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&should_check_for_sync
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

                                    #[allow(non_exhaustive_omitted_patterns)]
                                    match tail.kind() { ty::Foreign(_) => true, _ => false, }
                                };
                        let forbid_unsized =
                            !(is_foreign_item && is_structurally_foreign_item());
                        wfcx.register_wf_obligation(span,
                            Some(WellFormedLoc::Ty(item_id)), item_ty.into());
                        if forbid_unsized {
                            let span = tcx.def_span(item_id);
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sized, span));
                        }
                        let should_check_for_sync =
                            should_check_for_sync && !is_foreign_item &&
                                    tcx.static_mutability(item_id.to_def_id()) ==
                                        Some(hir::Mutability::Not) &&
                                !tcx.is_thread_local_static(item_id.to_def_id());
                        if should_check_for_sync {
                            wfcx.register_bound(traits::ObligationCause::new(span,
                                    wfcx.body_def_id, ObligationCauseCode::SharedStatic),
                                wfcx.param_env, item_ty,
                                tcx.require_lang_item(LangItem::Sync, span));
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
1206pub(crate) fn check_static_item<'tcx>(
1207    tcx: TyCtxt<'tcx>,
1208    item_id: LocalDefId,
1209    ty: Ty<'tcx>,
1210    should_check_for_sync: bool,
1211) -> Result<(), ErrorGuaranteed> {
1212    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1213        if should_check_for_sync {
1214            check_eiis_static(tcx, item_id, ty);
1215        }
1216
1217        let span = tcx.ty_span(item_id);
1218        let loc = Some(WellFormedLoc::Ty(item_id));
1219        let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1220
1221        let is_foreign_item = tcx.is_foreign_item(item_id);
1222        let is_structurally_foreign_item = || {
1223            let tail = tcx.struct_tail_raw(
1224                item_ty,
1225                &ObligationCause::dummy(),
1226                |ty| wfcx.deeply_normalize(span, loc, ty),
1227                || {},
1228            );
1229
1230            matches!(tail.kind(), ty::Foreign(_))
1231        };
1232        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1233
1234        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1235        if forbid_unsized {
1236            let span = tcx.def_span(item_id);
1237            wfcx.register_bound(
1238                traits::ObligationCause::new(
1239                    span,
1240                    wfcx.body_def_id,
1241                    ObligationCauseCode::SizedConstOrStatic,
1242                ),
1243                wfcx.param_env,
1244                item_ty,
1245                tcx.require_lang_item(LangItem::Sized, span),
1246            );
1247        }
1248
1249        // Ensure that the end result is `Sync` in a non-thread local `static`.
1250        let should_check_for_sync = should_check_for_sync
1251            && !is_foreign_item
1252            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1253            && !tcx.is_thread_local_static(item_id.to_def_id());
1254
1255        if should_check_for_sync {
1256            wfcx.register_bound(
1257                traits::ObligationCause::new(
1258                    span,
1259                    wfcx.body_def_id,
1260                    ObligationCauseCode::SharedStatic,
1261                ),
1262                wfcx.param_env,
1263                item_ty,
1264                tcx.require_lang_item(LangItem::Sync, span),
1265            );
1266        }
1267        Ok(())
1268    })
1269}
1270
1271/// Runs checks common to both free consts and associated consts
1272{}
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_const_item",
                                "rustc_hir_analysis::check::wfcheck",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                ::tracing_core::__macro_support::Option::Some(1272u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("item_ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("item_ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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);
                        let mut res = Ok(());
                        if tcx.is_direct_const(def_id.into()) {
                            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 !tcx.features().generic_const_parameter_types() &&
                                    item_ty.has_param() {
                                res =
                                    Err(tcx.dcx().emit_err(ParamInTyOfConstParam {
                                                span,
                                                ty: item_ty,
                                            }));
                            }
                        }
                        if let Some(direct_rhs) = tcx.const_of_item(def_id) {
                            let raw_ct = direct_rhs.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))));
                        }
                        res
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1272",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1272u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(wfcx), ret)]
1273pub(super) fn check_const_item<'tcx>(
1274    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1275    def_id: LocalDefId,
1276    item_ty: Ty<'tcx>,
1277) -> Result<(), ErrorGuaranteed> {
1278    let tcx = wfcx.tcx();
1279    let span = tcx.def_span(def_id);
1280
1281    let mut res = Ok(());
1282
1283    if tcx.is_direct_const(def_id.into()) {
1284        if !tcx.features().const_param_ty_unchecked() {
1285            wfcx.register_bound(
1286                ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1287                wfcx.param_env,
1288                item_ty,
1289                tcx.require_lang_item(LangItem::ConstParamTy, span),
1290            );
1291        }
1292        // FIXME(min_generic_const_args): We *might* want to move this check to `type_of`, so we can
1293        // return `ty::Error` if it references invalid params. However, doing so is hard, because
1294        // `type_of` doesn't know if it's a direct const - `const_of_item` determines that, and
1295        // `const_of_item` calls `type_of`.
1296        if !tcx.features().generic_const_parameter_types() && item_ty.has_param() {
1297            res = Err(tcx.dcx().emit_err(ParamInTyOfConstParam { span, ty: item_ty }));
1298        }
1299    }
1300
1301    if let Some(direct_rhs) = tcx.const_of_item(def_id) {
1302        let raw_ct = direct_rhs.instantiate_identity();
1303        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1304        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1305
1306        wfcx.register_obligation(Obligation::new(
1307            tcx,
1308            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1309            wfcx.param_env,
1310            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1311        ));
1312    }
1313
1314    res
1315}
1316
1317{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1317u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            enter_wf_checking_ctxt(tcx, item.owner_id.def_id,
                |wfcx|
                    {
                        match impl_.of_trait {
                            Some(of_trait) => {
                                let trait_ref =
                                    tcx.impl_trait_ref(item.owner_id).instantiate_identity();
                                tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
                                let trait_span = of_trait.trait_ref.path.span;
                                let trait_ref =
                                    wfcx.deeply_normalize(trait_span,
                                        Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                        trait_ref);
                                let trait_pred =
                                    ty::TraitClause {
                                        trait_ref,
                                        polarity: ty::ClausePolarity::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 /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1386",
                                                        "rustc_hir_analysis::check::wfcheck",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1386u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                                        ::tracing_core::field::FieldSet::new(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("obligations");
                                                                            NAME.as_str()
                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                wfcx.register_obligations(obligations);
                            }
                            None => {
                                let self_ty =
                                    tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
                                let self_ty =
                                    wfcx.deeply_normalize(item.span,
                                        Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                        Unnormalized::new_wip(self_ty));
                                wfcx.register_wf_obligation(impl_.self_ty.span,
                                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
                                    self_ty.into());
                            }
                        }
                        check_where_clauses(wfcx, item.owner_id.def_id);
                        Ok(())
                    })
        }
    }
}#[instrument(level = "debug", skip(tcx, impl_))]
1318fn check_impl<'tcx>(
1319    tcx: TyCtxt<'tcx>,
1320    item: &'tcx hir::Item<'tcx>,
1321    impl_: &hir::Impl<'_>,
1322) -> Result<(), ErrorGuaranteed> {
1323    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1324        match impl_.of_trait {
1325            Some(of_trait) => {
1326                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1327                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1328                // case other `Foo` impls are incoherent.
1329                tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1330                let trait_span = of_trait.trait_ref.path.span;
1331                let trait_ref = wfcx.deeply_normalize(
1332                    trait_span,
1333                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1334                    trait_ref,
1335                );
1336                let trait_pred =
1337                    ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive };
1338                let mut obligations = traits::wf::trait_obligations(
1339                    wfcx.infcx,
1340                    wfcx.param_env,
1341                    wfcx.body_def_id,
1342                    trait_pred,
1343                    trait_span,
1344                    item,
1345                );
1346                for obligation in &mut obligations {
1347                    if obligation.cause.span != trait_span {
1348                        // We already have a better span.
1349                        continue;
1350                    }
1351                    if let Some(pred) = obligation.predicate.as_trait_clause()
1352                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1353                    {
1354                        obligation.cause.span = impl_.self_ty.span;
1355                    }
1356                    if let Some(pred) = obligation.predicate.as_projection_clause()
1357                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1358                    {
1359                        obligation.cause.span = impl_.self_ty.span;
1360                    }
1361                }
1362
1363                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1364                if tcx.is_conditionally_const(item.owner_id.def_id) {
1365                    for (bound, _) in
1366                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1367                    {
1368                        let bound = wfcx.normalize(
1369                            item.span,
1370                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1371                            bound,
1372                        );
1373                        wfcx.register_obligation(Obligation::new(
1374                            tcx,
1375                            ObligationCause::new(
1376                                impl_.self_ty.span,
1377                                wfcx.body_def_id,
1378                                ObligationCauseCode::WellFormed(None),
1379                            ),
1380                            wfcx.param_env,
1381                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1382                        ))
1383                    }
1384                }
1385
1386                debug!(?obligations);
1387                wfcx.register_obligations(obligations);
1388            }
1389            None => {
1390                let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1391                let self_ty = wfcx.deeply_normalize(
1392                    item.span,
1393                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1394                    Unnormalized::new_wip(self_ty),
1395                );
1396                wfcx.register_wf_obligation(
1397                    impl_.self_ty.span,
1398                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1399                    self_ty.into(),
1400                );
1401            }
1402        }
1403
1404        check_where_clauses(wfcx, item.owner_id.def_id);
1405        Ok(())
1406    })
1407}
1408
1409/// Checks where-clauses and inline bounds that are declared on `def_id`.
1410{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1410u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = wfcx.infcx;
            let tcx = wfcx.tcx();
            let gen_clauses = tcx.clauses_of(def_id.to_def_id());
            let generics = tcx.generics_of(def_id);
            for param in &generics.own_params {
                if let Some(default) =
                        param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
                    {
                    if !default.has_param() {
                        wfcx.register_wf_obligation(tcx.def_span(param.def_id),
                            (#[allow(non_exhaustive_omitted_patterns)] match param.kind
                                    {
                                    GenericParamDefKind::Type { .. } => true,
                                    _ => false,
                                }).then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
                            default.as_term().unwrap());
                    } else {
                        let GenericArgKind::Const(ct) =
                            default.kind() else { continue; };
                        let ct_ty =
                            match ct.kind() {
                                ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
                                    ty::ConstKind::Bound(_, _) =>
                                    ::core::panicking::panic("internal error: entered unreachable code"),
                                ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
                                    continue,
                                ty::ConstKind::Value(cv) => cv.ty,
                                ty::ConstKind::Alias(_, alias_const) => {
                                    alias_const.type_of(infcx.tcx).skip_norm_wip()
                                }
                                ty::ConstKind::Param(param_ct) => {
                                    param_ct.find_const_ty_from_env(wfcx.param_env)
                                }
                            };
                        let param_ty =
                            tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
                        if !ct_ty.has_param() && !param_ty.has_param() {
                            let cause =
                                traits::ObligationCause::new(tcx.def_span(param.def_id),
                                    wfcx.body_def_id, ObligationCauseCode::WellFormed(None));
                            wfcx.register_obligation(Obligation::new(tcx, cause,
                                    wfcx.param_env,
                                    ty::ClauseKind::ConstArgHasType(ct, param_ty)));
                        }
                    }
                }
            }
            let args =
                GenericArgs::for_item(tcx, def_id.to_def_id(),
                    |param, _|
                        {
                            if param.index >= generics.parent_count as u32 &&
                                        let Some(default) =
                                            param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
                                    && !default.has_param() {
                                return default;
                            }
                            tcx.mk_param_from_def(param)
                        });
            let default_obligations =
                gen_clauses.clauses.iter().flat_map(|&(clause, sp)|
                            {
                                struct CountParams {
                                    params: FxHashSet<u32>,
                                }
                                #[automatically_derived]
                                impl ::core::default::Default for CountParams {
                                    #[inline]
                                    fn default() -> Self {
                                        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 =
                                    clause.visit_with(&mut param_count).is_break();
                                let instantiated_clause =
                                    ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
                                if instantiated_clause.skip_normalization().has_non_region_param()
                                            || param_count.params.len() > 1 || has_region {
                                    None
                                } else if gen_clauses.clauses.iter().any(|&(p, _)|
                                            Unnormalized::new_wip(p) == instantiated_clause) {
                                    None
                                } else { Some((instantiated_clause, sp)) }
                            }).map(|(clause, sp)|
                        {
                            let clause = wfcx.normalize(sp, None, clause);
                            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, clause)
                        });
            let gen_clauses = gen_clauses.instantiate_identity(tcx);
            let assoc_const_obligations: Vec<_> =
                gen_clauses.clauses.iter().copied().zip(gen_clauses.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 (&gen_clauses.clauses.len(), &gen_clauses.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 =
                gen_clauses.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))]
1411pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1412    let infcx = wfcx.infcx;
1413    let tcx = wfcx.tcx();
1414
1415    let gen_clauses = tcx.clauses_of(def_id.to_def_id());
1416    let generics = tcx.generics_of(def_id);
1417
1418    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1419    // For example, this forbids the declaration:
1420    //
1421    //     struct Foo<T = Vec<[u32]>> { .. }
1422    //
1423    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1424    for param in &generics.own_params {
1425        if let Some(default) = param
1426            .default_value(tcx)
1427            .map(ty::EarlyBinder::instantiate_identity)
1428            .map(Unnormalized::skip_norm_wip)
1429        {
1430            // Ignore dependent defaults -- that is, where the default of one type
1431            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1432            // be sure if it will error or not as user might always specify the other.
1433            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1434            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1435            // eagerly error but we don't as we have `ConstKind::Alias(.., [N, M])`.
1436            if !default.has_param() {
1437                wfcx.register_wf_obligation(
1438                    tcx.def_span(param.def_id),
1439                    matches!(param.kind, GenericParamDefKind::Type { .. })
1440                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1441                    default.as_term().unwrap(),
1442                );
1443            } else {
1444                // If we've got a generic const parameter we still want to check its
1445                // type is correct in case both it and the param type are fully concrete.
1446                let GenericArgKind::Const(ct) = default.kind() else {
1447                    continue;
1448                };
1449
1450                let ct_ty = match ct.kind() {
1451                    ty::ConstKind::Infer(_)
1452                    | ty::ConstKind::Placeholder(_)
1453                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1454                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1455                    ty::ConstKind::Value(cv) => cv.ty,
1456                    ty::ConstKind::Alias(_, alias_const) => {
1457                        alias_const.type_of(infcx.tcx).skip_norm_wip()
1458                    }
1459                    ty::ConstKind::Param(param_ct) => {
1460                        param_ct.find_const_ty_from_env(wfcx.param_env)
1461                    }
1462                };
1463
1464                let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1465                if !ct_ty.has_param() && !param_ty.has_param() {
1466                    let cause = traits::ObligationCause::new(
1467                        tcx.def_span(param.def_id),
1468                        wfcx.body_def_id,
1469                        ObligationCauseCode::WellFormed(None),
1470                    );
1471                    wfcx.register_obligation(Obligation::new(
1472                        tcx,
1473                        cause,
1474                        wfcx.param_env,
1475                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1476                    ));
1477                }
1478            }
1479        }
1480    }
1481
1482    // Check that trait clauses are WF when params are instantiated with their defaults.
1483    // We don't want to overly constrain the clauses that may be written but we want to
1484    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1485    // Therefore we check if a clause which contains a single type param
1486    // with a concrete default is WF with that default instantiated.
1487    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1488    //
1489    // First we build the defaulted generic parameters.
1490    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1491        if param.index >= generics.parent_count as u32
1492            // If the param has a default, ...
1493            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1494            // ... and it's not a dependent default, ...
1495            && !default.has_param()
1496        {
1497            // ... then instantiate it with the default.
1498            return default;
1499        }
1500        tcx.mk_param_from_def(param)
1501    });
1502
1503    // Now we build the instantiated clauses.
1504    let default_obligations = gen_clauses
1505        .clauses
1506        .iter()
1507        .flat_map(|&(clause, sp)| {
1508            #[derive(Default)]
1509            struct CountParams {
1510                params: FxHashSet<u32>,
1511            }
1512            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1513                type Result = ControlFlow<()>;
1514                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1515                    if let ty::Param(param) = t.kind() {
1516                        self.params.insert(param.index);
1517                    }
1518                    t.super_visit_with(self)
1519                }
1520
1521                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1522                    ControlFlow::Break(())
1523                }
1524
1525                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1526                    if let ty::ConstKind::Param(param) = c.kind() {
1527                        self.params.insert(param.index);
1528                    }
1529                    c.super_visit_with(self)
1530                }
1531            }
1532            let mut param_count = CountParams::default();
1533            let has_region = clause.visit_with(&mut param_count).is_break();
1534            let instantiated_clause = ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
1535            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1536            // or clauses with multiple params.
1537            if instantiated_clause.skip_normalization().has_non_region_param()
1538                || param_count.params.len() > 1
1539                || has_region
1540            {
1541                None
1542            } else if gen_clauses
1543                .clauses
1544                .iter()
1545                .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_clause)
1546            {
1547                // Avoid duplication of clauses that contain no parameters, for example.
1548                None
1549            } else {
1550                Some((instantiated_clause, sp))
1551            }
1552        })
1553        .map(|(clause, sp)| {
1554            // Convert each of those into an obligation. So if you have
1555            // something like `struct Foo<T: Copy = String>`, we would
1556            // take that clause `T: Copy`, instantiated with `String: Copy`
1557            // (actually that happens in the previous `flat_map` call),
1558            // and then try to prove it (in this case, we'll fail).
1559            //
1560            // Note the subtle difference from how we handle `gen_clauses`
1561            // below: there, we are not trying to prove those clauses
1562            // to be *true* but merely *well-formed*.
1563            let clause = wfcx.normalize(sp, None, clause);
1564            let cause = traits::ObligationCause::new(
1565                sp,
1566                wfcx.body_def_id,
1567                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1568            );
1569            Obligation::new(tcx, cause, wfcx.param_env, clause)
1570        });
1571
1572    let gen_clauses = gen_clauses.instantiate_identity(tcx);
1573
1574    let assoc_const_obligations: Vec<_> = gen_clauses
1575        .clauses
1576        .iter()
1577        .copied()
1578        .zip(gen_clauses.spans.iter().copied())
1579        .filter_map(|(clause, sp)| {
1580            let clause = clause.skip_norm_wip();
1581            let proj = clause.as_projection_clause()?;
1582            let pred_binder = proj
1583                .map_bound(|pred| {
1584                    pred.term.as_const().map(|ct| {
1585                        let assoc_const_ty =
1586                            pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1587                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1588                    })
1589                })
1590                .transpose();
1591            pred_binder.map(|pred_binder| {
1592                let cause = traits::ObligationCause::new(
1593                    sp,
1594                    wfcx.body_def_id,
1595                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1596                );
1597                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1598            })
1599        })
1600        .collect();
1601
1602    assert_eq!(gen_clauses.clauses.len(), gen_clauses.spans.len());
1603    let wf_obligations = gen_clauses.into_iter().flat_map(|(p, sp)| {
1604        traits::wf::clause_obligations(
1605            infcx,
1606            wfcx.param_env,
1607            wfcx.body_def_id,
1608            p.skip_norm_wip(),
1609            sp,
1610        )
1611    });
1612    let obligations: Vec<_> =
1613        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1614    wfcx.register_obligations(obligations);
1615}
1616
1617{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1617u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = wfcx.tcx();
            let mut sig =
                tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
            let arg_span =
                |idx|
                    hir_decl.inputs.get(idx).map_or(hir_decl.output.span(),
                        |arg: &hir::Ty<'_>| arg.span);
            sig.inputs_and_output =
                tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx,
                                ty)|
                            {
                                wfcx.deeply_normalize(arg_span(idx),
                                    Some(WellFormedLoc::Param {
                                            function: def_id,
                                            param_idx: idx,
                                        }), Unnormalized::new_wip(ty))
                            }));
            for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
                wfcx.register_wf_obligation(arg_span(idx),
                    Some(WellFormedLoc::Param {
                            function: def_id,
                            param_idx: idx,
                        }), ty.into());
            }
            check_where_clauses(wfcx, def_id);
            if sig.abi() == ExternAbi::RustCall {
                let span = tcx.def_span(def_id);
                let has_implicit_self =
                    hir_decl.implicit_self().has_implicit_self();
                let mut inputs =
                    sig.inputs().iter().skip(if has_implicit_self {
                            1
                        } else { 0 });
                if let Some(ty) = inputs.next() {
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(LangItem::Tuple, span));
                    wfcx.register_bound(ObligationCause::new(span,
                            wfcx.body_def_id, ObligationCauseCode::RustCall),
                        wfcx.param_env, *ty,
                        tcx.require_lang_item(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))]
1618fn check_fn_or_method<'tcx>(
1619    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1620    sig: ty::PolyFnSig<'tcx>,
1621    hir_decl: &hir::FnDecl<'_>,
1622    def_id: LocalDefId,
1623) {
1624    let tcx = wfcx.tcx();
1625    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1626
1627    // Normalize the input and output types one at a time, using a different
1628    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1629    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1630    // for each type, preventing the HIR wf check from generating
1631    // a nice error message.
1632    let arg_span =
1633        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1634
1635    sig.inputs_and_output =
1636        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1637            wfcx.deeply_normalize(
1638                arg_span(idx),
1639                Some(WellFormedLoc::Param {
1640                    function: def_id,
1641                    // Note that the `param_idx` of the output type is
1642                    // one greater than the index of the last input type.
1643                    param_idx: idx,
1644                }),
1645                Unnormalized::new_wip(ty),
1646            )
1647        }));
1648
1649    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1650        wfcx.register_wf_obligation(
1651            arg_span(idx),
1652            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1653            ty.into(),
1654        );
1655    }
1656
1657    check_where_clauses(wfcx, def_id);
1658
1659    if sig.abi() == ExternAbi::RustCall {
1660        let span = tcx.def_span(def_id);
1661        let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1662        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1663        // Check that the argument is a tuple and is sized
1664        if let Some(ty) = inputs.next() {
1665            wfcx.register_bound(
1666                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1667                wfcx.param_env,
1668                *ty,
1669                tcx.require_lang_item(LangItem::Tuple, span),
1670            );
1671            wfcx.register_bound(
1672                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1673                wfcx.param_env,
1674                *ty,
1675                tcx.require_lang_item(LangItem::Sized, span),
1676            );
1677        } else {
1678            tcx.dcx().span_err(
1679                hir_decl.inputs.last().map_or(span, |input| input.span),
1680                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1681            );
1682        }
1683        // No more inputs other than the `self` type and the tuple type
1684        if inputs.next().is_some() {
1685            tcx.dcx().span_err(
1686                hir_decl.inputs.last().map_or(span, |input| input.span),
1687                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1688            );
1689        }
1690    }
1691
1692    // If the function has a body, additionally require that the return type is sized.
1693    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1694        let span = match hir_decl.output {
1695            hir::FnRetTy::Return(ty) => ty.span,
1696            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1697        };
1698
1699        wfcx.register_bound(
1700            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1701            wfcx.param_env,
1702            sig.output(),
1703            tcx.require_lang_item(LangItem::Sized, span),
1704        );
1705    }
1706}
1707
1708/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1709#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ArbitrarySelfTypesLevel { }
#[automatically_derived]
impl ::core::clone::Clone for ArbitrarySelfTypesLevel {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ArbitrarySelfTypesLevel { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ArbitrarySelfTypesLevel { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ArbitrarySelfTypesLevel {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
1710enum ArbitrarySelfTypesLevel {
1711    Basic,        // just arbitrary_self_types
1712    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1713}
1714
1715{}
#[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("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1715u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("method")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("method");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.ocx.infcx.tcx;
            let mut span = tcx.def_span(self.body_def_id);
            let empty_env = ty::ParamEnv::empty();
            let clauses_with_span =
                tcx.clauses_of(self.body_def_id).clauses.iter().copied();
            let implied_obligations =
                traits::elaborate(tcx, clauses_with_span);
            for (clause, obligation_span) in implied_obligations {
                match clause.kind().skip_binder() {
                    ty::ClauseKind::WellFormed(..) |
                        ty::ClauseKind::UnstableFeature(..) => continue,
                    _ => {}
                }
                if clause.is_global() &&
                        !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
                    let clause =
                        self.normalize(span, None, Unnormalized::new_wip(clause));
                    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, clause);
                    self.ocx.register_obligation(obligation);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2300    fn check_false_global_bounds(&mut self) {
2301        let tcx = self.ocx.infcx.tcx;
2302        let mut span = tcx.def_span(self.body_def_id);
2303        let empty_env = ty::ParamEnv::empty();
2304
2305        let clauses_with_span = tcx.clauses_of(self.body_def_id).clauses.iter().copied();
2306        // Check elaborated bounds.
2307        let implied_obligations = traits::elaborate(tcx, clauses_with_span);
2308
2309        for (clause, obligation_span) in implied_obligations {
2310            match clause.kind().skip_binder() {
2311                // We lower empty bounds like `Vec<dyn Copy>:` as
2312                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2313                // regular WF checking
2314                ty::ClauseKind::WellFormed(..)
2315                // Unstable feature goals cannot be proven in an empty environment so skip them
2316                | ty::ClauseKind::UnstableFeature(..) => continue,
2317                _ => {}
2318            }
2319
2320            // Match the existing behavior.
2321            if clause.is_global() && !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2322                let clause = self.normalize(span, None, Unnormalized::new_wip(clause));
2323
2324                // only use the span of the predicate clause (#90869)
2325                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2326                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2327                    span = predicates
2328                        .iter()
2329                        // There seems to be no better way to find out which predicate we are in
2330                        .find(|pred| pred.span.contains(obligation_span))
2331                        .map(|pred| pred.span)
2332                        .unwrap_or(obligation_span);
2333                }
2334
2335                let obligation = Obligation::new(
2336                    tcx,
2337                    traits::ObligationCause::new(
2338                        span,
2339                        self.body_def_id,
2340                        ObligationCauseCode::TrivialBound,
2341                    ),
2342                    empty_env,
2343                    clause,
2344                );
2345                self.ocx.register_obligation(obligation);
2346            }
2347        }
2348    }
2349
2350    {}
#[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_test_binder_body",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2350u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("body")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("body");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let TestBinderBody { foralls, exists, constraints, predicates } =
                body;
            if !predicates.is_empty() {
                for (predicate, span) in predicates {
                    let cause =
                        traits::ObligationCause::misc(span, self.body_def_id);
                    let obligation =
                        Obligation::new(self.tcx(), cause, self.param_env,
                            predicate);
                    self.register_obligation(obligation);
                }
                match self.ocx.evaluate_obligations_error_on_ambiguity() {
                    TraitErrors::NoErrors => (),
                    TraitErrors::HasErrors(errors) => {
                        self.infcx.err_ctxt().report_fulfillment_errors(errors);
                        return;
                    }
                }
            }
            let constraints =
                match validate(self.tcx(), &constraints) {
                    Ok(()) => constraints,
                    Err(_guar) =>
                        ty::region_constraint::RegionConstraint::new_true(),
                };
            self.infcx.register_solver_region_constraint(constraints);
            for forall in foralls { self.check_test_binder_forall(forall); }
            for exists in exists { self.check_test_binder_exists(exists); }
            fn validate<'tcx>(tcx: TyCtxt<'tcx>,
                constraint: &SolverRegionConstraint<'tcx>)
                -> Result<(), ErrorGuaranteed> {
                let mut r = Ok(());
                let mut validate_and =
                    |and: &And<TyCtxt<'_>, _>|
                        {
                            for c in and.0.iter() {
                                match c {
                                    LeafRegionConstraint::Ambiguity(_) |
                                        LeafRegionConstraint::RegionOutlives(..) |
                                        LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (),
                                    LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) =>
                                        {
                                        if let ty::Placeholder(_) | ty::Param(_) = ty.kind()
                                            {} else {
                                            let mut err =
                                                tcx.dcx().struct_span_err(*span,
                                                    "the lhs of a ty outlives must be a placeholder");
                                            err.note(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("it is a {0}", ty))
                                                    }));
                                            err.note(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("and here it is `Debug`ged :3 {0:?}",
                                                                ty))
                                                    }));
                                            r = Err(err.emit_err());
                                        }
                                    }
                                }
                            }
                        };
                validate_and(&constraint.and_constraint);
                for and in constraint.or_constraint.0.iter() {
                    validate_and(and);
                }
                r
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2351    pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {
2352        let TestBinderBody { foralls, exists, constraints, predicates } = body;
2353        if !predicates.is_empty() {
2354            for (predicate, span) in predicates {
2355                let cause = traits::ObligationCause::misc(span, self.body_def_id);
2356                let obligation = Obligation::new(self.tcx(), cause, self.param_env, predicate);
2357                self.register_obligation(obligation);
2358            }
2359            match self.ocx.evaluate_obligations_error_on_ambiguity() {
2360                TraitErrors::NoErrors => (),
2361                TraitErrors::HasErrors(errors) => {
2362                    self.infcx.err_ctxt().report_fulfillment_errors(errors);
2363                    return;
2364                }
2365            }
2366        }
2367
2368        let constraints = match validate(self.tcx(), &constraints) {
2369            Ok(()) => constraints,
2370            Err(_guar) => ty::region_constraint::RegionConstraint::new_true(),
2371        };
2372
2373        self.infcx.register_solver_region_constraint(constraints);
2374
2375        for forall in foralls {
2376            self.check_test_binder_forall(forall);
2377        }
2378        for exists in exists {
2379            self.check_test_binder_exists(exists);
2380        }
2381
2382        fn validate<'tcx>(
2383            tcx: TyCtxt<'tcx>,
2384            constraint: &SolverRegionConstraint<'tcx>,
2385        ) -> Result<(), ErrorGuaranteed> {
2386            let mut r = Ok(());
2387
2388            let mut validate_and = |and: &And<TyCtxt<'_>, _>| {
2389                for c in and.0.iter() {
2390                    match c {
2391                        LeafRegionConstraint::Ambiguity(_)
2392                        | LeafRegionConstraint::RegionOutlives(..)
2393                        | LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (), // OK
2394                        LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) => {
2395                            // we can't check this during lowering, because the ty is a ty::Bound that gets
2396                            // instantiated with a placeholder when entering the containing forall.
2397                            if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
2398                                // all OK
2399                            } else {
2400                                let mut err = tcx.dcx().struct_span_err(
2401                                    *span,
2402                                    "the lhs of a ty outlives must be a placeholder",
2403                                );
2404                                err.note(format!("it is a {ty}"));
2405                                err.note(format!("and here it is `Debug`ged :3 {ty:?}"));
2406                                r = Err(err.emit_err());
2407                            }
2408                        }
2409                    }
2410                }
2411            };
2412
2413            validate_and(&constraint.and_constraint);
2414            for and in constraint.or_constraint.0.iter() {
2415                validate_and(and);
2416            }
2417
2418            r
2419        }
2420    }
2421
2422    {}
#[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_test_binder_forall",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2422u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("forall")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("forall");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&forall)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.infcx.enter_forall(forall.binder,
                |body|
                    {
                        let u = self.infcx.universe();
                        let mut builder = TransitiveRelationBuilder::default();
                        for &(r1, r2) in &body.region_outlives {
                            builder.add(r1, r2);
                        }
                        let assumptions =
                            ty::region_constraint::Assumptions::new_unelaborated(body.type_outlives,
                                builder.freeze());
                        self.infcx.insert_placeholder_assumptions(u,
                            Some(assumptions));
                        self.check_test_binder_body(body.value);
                        let solver_region_constraint =
                            self.infcx.get_solver_region_constraint();
                        let constraint =
                            ty::region_constraint::eagerly_handle_placeholders_in_universe(self.infcx,
                                    solver_region_constraint.without_spans(),
                                    u).with_spans(forall.span);
                        if let Some(assert_on_exit) = &forall.assert_on_exit {
                            self.check_test_binder_region_constraints(forall.span,
                                assert_on_exit, &constraint);
                        }
                        self.infcx.overwrite_solver_region_constraint(constraint);
                    });
        }
    }
}#[instrument(level = "debug", skip(self))]
2423    fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {
2424        self.infcx.enter_forall(forall.binder, |body| {
2425            let u = self.infcx.universe();
2426            let mut builder = TransitiveRelationBuilder::default();
2427            for &(r1, r2) in &body.region_outlives {
2428                builder.add(r1, r2);
2429            }
2430            // Deliberately unelaborated: the assumptions of a `forall` are exactly the ones
2431            // written down in the test, no extra ones hidden behind the scenes.
2432            let assumptions = ty::region_constraint::Assumptions::new_unelaborated(
2433                body.type_outlives,
2434                builder.freeze(),
2435            );
2436            self.infcx.insert_placeholder_assumptions(u, Some(assumptions));
2437            self.check_test_binder_body(body.value);
2438            let solver_region_constraint = self.infcx.get_solver_region_constraint();
2439            let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(
2440                self.infcx,
2441                solver_region_constraint.without_spans(),
2442                u,
2443            )
2444            .with_spans(forall.span);
2445            if let Some(assert_on_exit) = &forall.assert_on_exit {
2446                self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);
2447            }
2448            self.infcx.overwrite_solver_region_constraint(constraint);
2449        });
2450    }
2451
2452    {}
#[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_test_binder_region_constraints",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2452u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fallback_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fallback_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("actual")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("actual");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fallback_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            fn err<'tcx>(tcx: TyCtxt<'tcx>, expected_span: Span,
                expected: impl std::fmt::Debug, actual_span: Option<Span>,
                actual: impl std::fmt::Debug) {
                let mut err =
                    tcx.dcx().struct_span_err(expected_span,
                        "forall expect clause failed");
                if let Some(actual_span) = actual_span {
                    err.span_note(actual_span, "constraint from here");
                }
                err.note(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected: {0:#?}",
                                    expected))
                        }));
                err.note(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
                        }));
                err.emit();
            }
            let span_of_and =
                |c: &And<_, _>|
                    {
                        c.0.iter().map(|leaf|
                                    leaf.span()).reduce(|span: Span, acc| acc.to(span))
                    };
            let span_of_or =
                |c: &Or<_, _>|
                    {
                        c.0.iter().flat_map(|and|
                                    span_of_and(and)).reduce(|span, acc| acc.to(span))
                    };
            let check_leaf_constraint =
                |expected: LeafRegionConstraint<_, _>,
                    actual: LeafRegionConstraint<_, _>|
                    {
                        if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected,
                                    expected_span) = expected &&
                                let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual,
                                    actual_span) = actual {
                            let expected_anon =
                                self.tcx().anonymize_bound_vars(expected);
                            let actual_anon = self.tcx().anonymize_bound_vars(actual);
                            if expected_anon != actual_anon {
                                let mut err =
                                    self.tcx().dcx().struct_span_err(expected_span,
                                        "forall expect clause failed");
                                err.span_note(actual_span, "constraint from here");
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("expected: {0:#?}",
                                                    expected))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("expected_anon: {0:#?}",
                                                    expected_anon))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("actual_anon: {0:#?}",
                                                    actual_anon))
                                        }));
                                err.emit();
                            }
                        } else if expected.clone().without_span() !=
                                actual.clone().without_span() {
                            err(self.tcx(), expected.span(), expected,
                                Some(actual.span()), actual);
                        }
                    };
            let check_and_constraint =
                |expected: And<_, _>, actual: And<_, _>|
                    {
                        if expected.0.len() != actual.0.len() {
                            err(self.tcx(),
                                span_of_and(&expected).unwrap_or(fallback_span), expected,
                                span_of_and(&actual), actual)
                        } else {
                            for (expected, actual) in
                                expected.0.into_iter().zip(actual.0.into_iter()) {
                                check_leaf_constraint(expected, actual);
                            }
                        }
                    };
            let check_or_constraint =
                |expected: Or<_, _>, actual: Or<_, _>|
                    {
                        if expected.0.len() != actual.0.len() {
                            err(self.tcx(),
                                span_of_or(&expected).unwrap_or(fallback_span), expected,
                                span_of_or(&actual), actual)
                        } else {
                            for (expected, actual) in
                                expected.0.into_iter().zip(actual.0.into_iter()) {
                                check_and_constraint(expected, actual);
                            }
                        }
                    };
            check_or_constraint(expected.or_constraint.clone(),
                actual.or_constraint.clone());
            check_and_constraint(expected.and_constraint.clone(),
                actual.and_constraint.clone());
        }
    }
}#[instrument(level = "debug", skip(self))]
2453    fn check_test_binder_region_constraints(
2454        &self,
2455        fallback_span: Span,
2456        expected: &SolverRegionConstraint<'tcx>,
2457        actual: &SolverRegionConstraint<'tcx>,
2458    ) {
2459        fn err<'tcx>(
2460            tcx: TyCtxt<'tcx>,
2461            expected_span: Span,
2462            expected: impl std::fmt::Debug,
2463            actual_span: Option<Span>,
2464            actual: impl std::fmt::Debug,
2465        ) {
2466            let mut err = tcx.dcx().struct_span_err(expected_span, "forall expect clause failed");
2467            if let Some(actual_span) = actual_span {
2468                err.span_note(actual_span, "constraint from here");
2469            }
2470            err.note(format!("expected: {expected:#?}"));
2471            err.note(format!("actual: {actual:#?}"));
2472            err.emit();
2473        }
2474
2475        let span_of_and = |c: &And<_, _>| {
2476            c.0.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span))
2477        };
2478
2479        let span_of_or = |c: &Or<_, _>| {
2480            c.0.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span))
2481        };
2482
2483        let check_leaf_constraint =
2484            |expected: LeafRegionConstraint<_, _>, actual: LeafRegionConstraint<_, _>| {
2485                if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected, expected_span) =
2486                    expected
2487                    && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual, actual_span) = actual
2488                {
2489                    let expected_anon = self.tcx().anonymize_bound_vars(expected);
2490                    let actual_anon = self.tcx().anonymize_bound_vars(actual);
2491                    if expected_anon != actual_anon {
2492                        let mut err = self
2493                            .tcx()
2494                            .dcx()
2495                            .struct_span_err(expected_span, "forall expect clause failed");
2496                        err.span_note(actual_span, "constraint from here");
2497                        err.note(format!("expected: {expected:#?}"));
2498                        err.note(format!("actual: {actual:#?}"));
2499                        err.note(format!("expected_anon: {expected_anon:#?}"));
2500                        err.note(format!("actual_anon: {actual_anon:#?}"));
2501                        err.emit();
2502                    }
2503                } else if expected.clone().without_span() != actual.clone().without_span() {
2504                    err(self.tcx(), expected.span(), expected, Some(actual.span()), actual);
2505                }
2506            };
2507
2508        let check_and_constraint = |expected: And<_, _>, actual: And<_, _>| {
2509            if expected.0.len() != actual.0.len() {
2510                err(
2511                    self.tcx(),
2512                    span_of_and(&expected).unwrap_or(fallback_span),
2513                    expected,
2514                    span_of_and(&actual),
2515                    actual,
2516                )
2517            } else {
2518                for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2519                    check_leaf_constraint(expected, actual);
2520                }
2521            }
2522        };
2523
2524        let check_or_constraint = |expected: Or<_, _>, actual: Or<_, _>| {
2525            if expected.0.len() != actual.0.len() {
2526                err(
2527                    self.tcx(),
2528                    span_of_or(&expected).unwrap_or(fallback_span),
2529                    expected,
2530                    span_of_or(&actual),
2531                    actual,
2532                )
2533            } else {
2534                for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2535                    check_and_constraint(expected, actual);
2536                }
2537            }
2538        };
2539
2540        check_or_constraint(expected.or_constraint.clone(), actual.or_constraint.clone());
2541        check_and_constraint(expected.and_constraint.clone(), actual.and_constraint.clone());
2542    }
2543
2544    {}
#[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_test_binder_exists",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2544u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("exists")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("exists");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&exists)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let body =
                self.infcx.instantiate_binder_with_fresh_vars(exists.span,
                    BoundRegionConversionTime::HigherRankedType, exists.binder);
            self.check_test_binder_body(body);
        }
    }
}#[instrument(level = "debug", skip(self))]
2545    fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {
2546        let body = self.infcx.instantiate_binder_with_fresh_vars(
2547            exists.span,
2548            BoundRegionConversionTime::HigherRankedType,
2549            exists.binder,
2550        );
2551        self.check_test_binder_body(body);
2552    }
2553}
2554
2555pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2556    let items = tcx.hir_crate_items(());
2557    let res =
2558        items
2559            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2560            .and(
2561                items.par_impl_items(|item| {
2562                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2563                }),
2564            )
2565            .and(items.par_trait_items(|item| {
2566                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2567            }))
2568            .and(items.par_foreign_items(|item| {
2569                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2570            }))
2571            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2572            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2573
2574    super::entry::check_for_entry_fn(tcx)?;
2575
2576    res
2577}
2578
2579fn lint_redundant_lifetimes<'tcx>(
2580    tcx: TyCtxt<'tcx>,
2581    owner_id: LocalDefId,
2582    outlives_env: &OutlivesEnvironment<'tcx>,
2583) {
2584    let def_kind = tcx.def_kind(owner_id);
2585    match def_kind {
2586        DefKind::Struct
2587        | DefKind::Union
2588        | DefKind::Enum
2589        | DefKind::Trait
2590        | DefKind::TraitAlias
2591        | DefKind::Fn
2592        | DefKind::Const
2593        | DefKind::Impl { of_trait: _ }
2594        | DefKind::TestBinderConstraints => {
2595            // Proceed
2596        }
2597        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2598            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2599                // Don't check for redundant lifetimes for associated items of trait
2600                // implementations, since the signature is required to be compatible
2601                // with the trait, even if the implementation implies some lifetimes
2602                // are redundant.
2603                return;
2604            }
2605        }
2606        DefKind::Mod
2607        | DefKind::Variant
2608        | DefKind::TyAlias
2609        | DefKind::ForeignTy
2610        | DefKind::TyParam
2611        | DefKind::ConstParam
2612        | DefKind::Static { .. }
2613        | DefKind::Ctor(_, _)
2614        | DefKind::Macro(_)
2615        | DefKind::ExternCrate
2616        | DefKind::Use
2617        | DefKind::ForeignMod
2618        | DefKind::AnonConst
2619        | DefKind::OpaqueTy
2620        | DefKind::Field
2621        | DefKind::LifetimeParam
2622        | DefKind::GlobalAsm
2623        | DefKind::Closure
2624        | DefKind::SyntheticCoroutineBody => return,
2625    }
2626
2627    // The ordering of this lifetime map is a bit subtle.
2628    //
2629    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2630    // where we can prove that `'candidate = 'victim`.
2631    //
2632    // `'static` must come first in this list because we can never replace `'static` with
2633    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2634    // suggest replacing `'a` with `'static`.
2635    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];
2636    lifetimes.extend(
2637        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2638    );
2639    // If we are in a function, add its late-bound lifetimes too.
2640    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2641        for (idx, var) in tcx
2642            .fn_sig(owner_id)
2643            .instantiate_identity()
2644            .skip_norm_wip()
2645            .bound_vars()
2646            .iter()
2647            .enumerate()
2648        {
2649            let ty::BoundVariableKind::Region(kind) = var else { continue };
2650            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2651            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2652        }
2653    }
2654    lifetimes.retain(|candidate| candidate.is_named(tcx));
2655
2656    // Keep track of lifetimes which have already been replaced with other lifetimes.
2657    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2658    // both `'a` and `'b`.
2659    let mut shadowed = FxHashSet::default();
2660
2661    for (idx, &candidate) in lifetimes.iter().enumerate() {
2662        // Don't suggest removing a lifetime twice. We only need to check this
2663        // here and not up in the `victim` loop because equality is transitive,
2664        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2665        // A's victim loop.
2666        if shadowed.contains(&candidate) {
2667            continue;
2668        }
2669
2670        for &victim in &lifetimes[(idx + 1)..] {
2671            // All region parameters should have a `DefId` available as:
2672            // - Late-bound parameters should be of the`BrNamed` variety,
2673            // since we get these signatures straight from `hir_lowering`.
2674            // - Early-bound parameters unconditionally have a `DefId` available.
2675            //
2676            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2677            // can't really suggest to remove them.
2678            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2679                continue;
2680            };
2681
2682            // Do not rename lifetimes not local to this item since they'll overlap
2683            // with the lint running on the parent. We still want to consider parent
2684            // lifetimes which make child lifetimes redundant, otherwise we would
2685            // have truncated the `identity_for_item` args above.
2686            if tcx.parent(def_id) != owner_id.to_def_id() {
2687                continue;
2688            }
2689
2690            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2691            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2692                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2693            {
2694                shadowed.insert(victim);
2695                tcx.emit_node_span_lint(
2696                    REDUNDANT_LIFETIMES,
2697                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2698                    tcx.def_span(def_id),
2699                    RedundantLifetimeArgsLint { candidate, victim },
2700                );
2701            }
2702        }
2703    }
2704}
2705
2706#[derive(const _: () =
    {
        impl<'_sess, 'tcx> rustc_errors::Diagnostic<'_sess> for
            RedundantLifetimeArgsLint<'tcx> {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                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)]
2707#[diag("unnecessary lifetime parameter `{$victim}`")]
2708#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2709struct RedundantLifetimeArgsLint<'tcx> {
2710    /// The lifetime we have found to be redundant.
2711    victim: ty::Region<'tcx>,
2712    // The lifetime we can replace the victim with.
2713    candidate: ty::Region<'tcx>,
2714}
2715
2716#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderBody<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderBody {
            foralls: ::core::clone::Clone::clone(&self.foralls),
            exists: ::core::clone::Clone::clone(&self.exists),
            constraints: ::core::clone::Clone::clone(&self.constraints),
            predicates: ::core::clone::Clone::clone(&self.predicates),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderBody<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "TestBinderBody", "foralls", &self.foralls, "exists",
            &self.exists, "constraints", &self.constraints, "predicates",
            &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderBody<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderBody {
                            foralls: __binding_0,
                            exists: __binding_1,
                            constraints: __binding_2,
                            predicates: __binding_3 } => {
                            TestBinderBody {
                                foralls: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                exists: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                constraints: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                                predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderBody {
                        foralls: __binding_0,
                        exists: __binding_1,
                        constraints: __binding_2,
                        predicates: __binding_3 } => {
                        TestBinderBody {
                            foralls: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            exists: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            constraints: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                            predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderBody<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderBody {
                        foralls: ref __binding_0,
                        exists: ref __binding_1,
                        constraints: ref __binding_2,
                        predicates: ref __binding_3 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2717pub(crate) struct TestBinderBody<'tcx> {
2718    pub foralls: Vec<TestBinderForall<'tcx>>,
2719    pub exists: Vec<TestBinderExists<'tcx>>,
2720    /// Constraints to be inserted directly into constraint storage to be proven
2721    pub constraints: SolverRegionConstraint<'tcx>,
2722    /// Constraints declared using `where` syntax, used via `register_obligation`
2723    pub predicates: Vec<(ty::Binder<'tcx, ty::ClauseKind<'tcx>>, Span)>,
2724}
2725
2726#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderForall<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderForall {
            span: ::core::clone::Clone::clone(&self.span),
            binder: ::core::clone::Clone::clone(&self.binder),
            assert_on_exit: ::core::clone::Clone::clone(&self.assert_on_exit),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderForall<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "TestBinderForall", "span", &self.span, "binder", &self.binder,
            "assert_on_exit", &&self.assert_on_exit)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderForall<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderForall {
                            span: __binding_0,
                            binder: __binding_1,
                            assert_on_exit: __binding_2 } => {
                            TestBinderForall {
                                span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                assert_on_exit: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderForall {
                        span: __binding_0,
                        binder: __binding_1,
                        assert_on_exit: __binding_2 } => {
                        TestBinderForall {
                            span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            assert_on_exit: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderForall<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderForall {
                        span: ref __binding_0,
                        binder: ref __binding_1,
                        assert_on_exit: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2727pub(crate) struct TestBinderForall<'tcx> {
2728    pub span: Span,
2729    pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,
2730    pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>,
2731}
2732
2733#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderExists<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderExists {
            span: ::core::clone::Clone::clone(&self.span),
            binder: ::core::clone::Clone::clone(&self.binder),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderExists<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TestBinderExists", "span", &self.span, "binder", &&self.binder)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderExists<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderExists { span: __binding_0, binder: __binding_1 }
                            => {
                            TestBinderExists {
                                span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderExists { span: __binding_0, binder: __binding_1 }
                        => {
                        TestBinderExists {
                            span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderExists<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderExists {
                        span: ref __binding_0, binder: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2734pub(crate) struct TestBinderExists<'tcx> {
2735    pub span: Span,
2736    pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,
2737}
2738
2739#[derive(#[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
    WithWhereClauses<'tcx, T> {
    #[inline]
    fn clone(&self) -> Self {
        WithWhereClauses {
            value: ::core::clone::Clone::clone(&self.value),
            type_outlives: ::core::clone::Clone::clone(&self.type_outlives),
            region_outlives: ::core::clone::Clone::clone(&self.region_outlives),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for
    WithWhereClauses<'tcx, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "WithWhereClauses", "value", &self.value, "type_outlives",
            &self.type_outlives, "region_outlives", &&self.region_outlives)
    }
}Debug, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for WithWhereClauses<'tcx, T> where
            T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        WithWhereClauses {
                            value: __binding_0,
                            type_outlives: __binding_1,
                            region_outlives: __binding_2 } => {
                            WithWhereClauses {
                                value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                type_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                region_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    WithWhereClauses {
                        value: __binding_0,
                        type_outlives: __binding_1,
                        region_outlives: __binding_2 } => {
                        WithWhereClauses {
                            value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            type_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            region_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for WithWhereClauses<'tcx, T> where
            T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    WithWhereClauses {
                        value: ref __binding_0,
                        type_outlives: ref __binding_1,
                        region_outlives: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2740pub(crate) struct WithWhereClauses<'tcx, T> {
2741    pub value: T,
2742
2743    // The where clauses on the forall. These eventually will probably get stored inside
2744    // `ty::Binder` but they're here for now.
2745    pub type_outlives: Vec<ty::Binder<'tcx, ty::OutlivesClause<'tcx, Ty<'tcx>>>>,
2746    pub region_outlives: Vec<(ty::Region<'tcx>, ty::Region<'tcx>)>,
2747}