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