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, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags, TypeFoldable,
33    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
34    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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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 = param_env.caller_bounds().chain(new_clauses.iter().copied());
581    // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
582    // i.e. traits::normalize_param_env_or_error
583    ty::ParamEnv::new(tcx, bounds)
584}
585
586/// We use the following trait as an example throughout this function.
587/// Specifically, let's assume that `to_check` here is the return type
588/// of `into_iter`, and the GAT we are checking this for is `Iter`.
589/// ```rust,ignore (this code fails due to this lint)
590/// trait IntoIter {
591///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
592///     type Item<'a>;
593///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
594/// }
595/// ```
596fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
597    tcx: TyCtxt<'tcx>,
598    param_env: ty::ParamEnv<'tcx>,
599    item_def_id: LocalDefId,
600    to_check: T,
601    wf_tys: &FxIndexSet<Ty<'tcx>>,
602    gat_def_id: LocalDefId,
603    gat_generics: &'tcx ty::Generics,
604) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
605    // The bounds we that we would require from `to_check`
606    let mut bounds = FxIndexSet::default();
607
608    let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
609
610    // If both regions and types are empty, then this GAT isn't in the
611    // set of types we are checking, and we shouldn't try to do clause analysis
612    // (particularly, doing so would end up with an empty set of clauses,
613    // since the current method would require none, and we take the
614    // intersection of requirements of all methods)
615    if types.is_empty() && regions.is_empty() {
616        return None;
617    }
618
619    for (region_a, region_a_idx) in &regions {
620        // Ignore `'static` lifetimes for the purpose of this lint: it's
621        // because we know it outlives everything and so doesn't give meaningful
622        // clues. Also ignore `ReError`, to avoid knock-down errors.
623        if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
624            continue;
625        }
626        // For each region argument (e.g., `'a` in our example), check for a
627        // relationship to the type arguments (e.g., `Self`). If there is an
628        // outlives relationship (`Self: 'a`), then we want to ensure that is
629        // reflected in a where clause on the GAT itself.
630        for (ty, ty_idx) in &types {
631            // In our example, requires that `Self: 'a`
632            if ty_known_to_outlive(
633                tcx,
634                item_def_id,
635                param_env,
636                wf_tys,
637                Unnormalized::new_wip(*ty),
638                *region_a,
639            ) {
640                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:640",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(640u32),
                        ::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);
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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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(&["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}");
642                // Translate into the generic parameters of the GAT. In
643                // our example, the type was `Self`, which will also be
644                // `Self` in the GAT.
645                let ty_param = gat_generics.param_at(*ty_idx, tcx);
646                let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
647                // Same for the region. In our example, 'a corresponds
648                // to the 'me parameter.
649                let region_param = gat_generics.param_at(*region_a_idx, tcx);
650                let region_param = ty::Region::new_early_param(
651                    tcx,
652                    ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
653                );
654                // The clause we expect to see. (In our example,
655                // `Self: 'me`.)
656                bounds.insert(
657                    ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty_param, region_param))
658                        .upcast(tcx),
659                );
660            }
661        }
662
663        // For each region argument (e.g., `'a` in our example), also check for a
664        // relationship to the other region arguments. If there is an outlives
665        // relationship, then we want to ensure that is reflected in the where clause
666        // on the GAT itself.
667        for (region_b, region_b_idx) in &regions {
668            // Again, skip `'static` because it outlives everything. Also, we trivially
669            // know that a region outlives itself. Also ignore `ReError`, to avoid
670            // knock-down errors.
671            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 {
672                continue;
673            }
674            if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
675                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:675",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(675u32),
                        ::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);
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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/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(&["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}");
677                // Translate into the generic parameters of the GAT.
678                let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
679                let region_a_param = ty::Region::new_early_param(
680                    tcx,
681                    ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
682                );
683                // Same for the region.
684                let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
685                let region_b_param = ty::Region::new_early_param(
686                    tcx,
687                    ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
688                );
689                // The clause we expect to see.
690                bounds.insert(
691                    ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
692                        region_a_param,
693                        region_b_param,
694                    ))
695                    .upcast(tcx),
696                );
697            }
698        }
699    }
700
701    Some(bounds)
702}
703
704/// TypeVisitor that looks for uses of GATs like
705/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
706/// the two vectors, `regions` and `types` (depending on their kind). For each
707/// parameter `Pi` also track the index `i`.
708struct GATArgsCollector<'tcx> {
709    gat: DefId,
710    // Which region appears and which parameter index its instantiated with
711    regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
712    // Which params appears and which parameter index its instantiated with
713    types: FxIndexSet<(Ty<'tcx>, usize)>,
714}
715
716impl<'tcx> GATArgsCollector<'tcx> {
717    fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
718        gat: DefId,
719        t: T,
720    ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
721        let mut visitor =
722            GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
723        t.visit_with(&mut visitor);
724        (visitor.regions, visitor.types)
725    }
726}
727
728impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
729    fn visit_ty(&mut self, t: Ty<'tcx>) {
730        match t.kind() {
731            &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
732                if def_id == self.gat =>
733            {
734                for (idx, arg) in args.iter().enumerate() {
735                    match arg.kind() {
736                        GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
737                            self.regions.insert((lt, idx));
738                        }
739                        GenericArgKind::Type(t) => {
740                            self.types.insert((t, idx));
741                        }
742                        _ => {}
743                    }
744                }
745            }
746            _ => {}
747        }
748        t.super_visit_with(self)
749    }
750}
751
752fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
753    let item_name = tcx.item_name(trait_item_def_id.to_def_id());
754    let trait_def_id = tcx.local_parent(trait_item_def_id);
755
756    let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
757        .skip(1)
758        .flat_map(|supertrait_def_id| {
759            tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
760        })
761        .collect();
762    if !shadowed.is_empty() {
763        let shadowee = if let [shadowed] = shadowed[..] {
764            diagnostics::SupertraitItemShadowee::Labeled {
765                span: tcx.def_span(shadowed.def_id),
766                supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
767            }
768        } else {
769            let (traits, spans): (Vec<_>, Vec<_>) = shadowed
770                .iter()
771                .map(|item| {
772                    (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
773                })
774                .unzip();
775            diagnostics::SupertraitItemShadowee::Several {
776                traits: traits.into(),
777                spans: spans.into(),
778            }
779        };
780
781        tcx.emit_node_span_lint(
782            SHADOWING_SUPERTRAIT_ITEMS,
783            tcx.local_def_id_to_hir_id(trait_item_def_id),
784            tcx.def_span(trait_item_def_id),
785            diagnostics::SupertraitItemShadowing {
786                item: item_name,
787                subtrait: tcx.item_name(trait_def_id.to_def_id()),
788                shadowee,
789            },
790        );
791    }
792}
793
794fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
795    match param.kind {
796        // We currently only check wf of const params here.
797        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
798
799        // Const parameters are well formed if their type is structural match.
800        ty::GenericParamDefKind::Const { .. } => {
801            let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
802            let span = tcx.def_span(param.def_id);
803            let def_id = param.def_id.expect_local();
804
805            if tcx.features().const_param_ty_unchecked() {
806                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
807                    wfcx.register_wf_obligation(span, WellFormedLoc::None, ty.into());
808                    Ok(())
809                })
810            } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
811                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
812                    wfcx.register_bound(
813                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
814                        wfcx.param_env,
815                        ty,
816                        tcx.require_lang_item(LangItem::ConstParamTy, span),
817                    );
818                    Ok(())
819                })
820            } else {
821                let span = || {
822                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
823                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
824                    else {
825                        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
826                    };
827                    span
828                };
829                let mut diag = match ty.kind() {
830                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
831                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
832                        span(),
833                        "using function pointers as const generic parameters is forbidden",
834                    ),
835                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
836                        span(),
837                        "using raw pointers as const generic parameters is forbidden",
838                    ),
839                    _ => {
840                        // Avoid showing "{type error}" to users. See #118179.
841                        ty.error_reported()?;
842
843                        tcx.dcx().struct_span_err(
844                            span(),
845                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
                ty))
    })format!(
846                                "`{ty}` is forbidden as the type of a const generic parameter",
847                            ),
848                        )
849                    }
850                };
851
852                diag.note("the only supported types are integers, `bool`, and `char`");
853
854                let cause = ObligationCause::misc(span(), def_id);
855                let adt_const_params_feature_string =
856                    " more complex and user defined types".to_string();
857                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
858                    tcx,
859                    tcx.param_env(param.def_id),
860                    ty,
861                    cause,
862                ) {
863                    // Can never implement `ConstParamTy`, don't suggest anything.
864                    Err(
865                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
866                        | ConstParamTyImplementationError::NonExhaustive(..)
867                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
868                    ) => None,
869                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
870                        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![
871                            (adt_const_params_feature_string, sym::min_adt_const_params),
872                            (
873                                " references to implement the `ConstParamTy` trait".into(),
874                                sym::unsized_const_params,
875                            ),
876                        ])
877                    }
878                    // May be able to implement `ConstParamTy`. Only emit the feature help
879                    // if the type is local, since the user may be able to fix the local type.
880                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
881                        fn ty_is_local(ty: Ty<'_>) -> bool {
882                            match ty.kind() {
883                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
884                                // Arrays and slices use the inner type's `ConstParamTy`.
885                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
886                                // `&` references use the inner type's `ConstParamTy`.
887                                // `&mut` are not supported.
888                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
889                                // Say that a tuple is local if any of its components are local.
890                                // This is not strictly correct, but it's likely that the user can fix the local component.
891                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
892                                _ => false,
893                            }
894                        }
895
896                        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![(
897                            adt_const_params_feature_string,
898                            sym::min_adt_const_params,
899                        )])
900                    }
901                    // Implements `ConstParamTy`, suggest adding the feature to enable.
902                    Ok(..) => {
903                        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)])
904                    }
905                };
906                if let Some(features) = may_suggest_feature {
907                    tcx.disabled_nightly_features(&mut diag, features);
908                }
909
910                Err(diag.emit_err())
911            }
912        }
913    }
914}
915
916{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(916u32),
                                    ::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))]
917pub(crate) fn check_associated_item(
918    tcx: TyCtxt<'_>,
919    def_id: LocalDefId,
920) -> Result<(), ErrorGuaranteed> {
921    let loc = WellFormedLoc::Ty(def_id);
922    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
923        let item = tcx.associated_item(def_id);
924
925        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
926        // other `Foo` impls are incoherent.
927        tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
928
929        let self_ty = match item.container {
930            ty::AssocContainer::Trait => tcx.types.self_param,
931            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
932                tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
933            }
934        };
935
936        let span = tcx.def_span(def_id);
937
938        match item.kind {
939            ty::AssocKind::Const { .. } => {
940                let ty = tcx.type_of(def_id).instantiate_identity();
941                let ty = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
942                wfcx.register_wf_obligation(span, loc, ty.into());
943
944                if item.defaultness(tcx).has_value() {
945                    let code = ObligationCauseCode::SizedConstOrStatic;
946                    wfcx.register_bound(
947                        ObligationCause::new(span, def_id, code),
948                        wfcx.param_env,
949                        ty,
950                        tcx.require_lang_item(LangItem::Sized, span),
951                    );
952                }
953
954                check_const_item(wfcx, def_id, ty)
955            }
956            ty::AssocKind::Fn { .. } => {
957                let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
958                let hir_sig =
959                    tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
960                check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
961                check_method_receiver(wfcx, hir_sig, item, self_ty)
962            }
963            ty::AssocKind::Type { .. } => {
964                if let ty::AssocContainer::Trait = item.container {
965                    check_associated_type_bounds(wfcx, item, span)
966                }
967                if item.defaultness(tcx).has_value() {
968                    let ty = tcx.type_of(def_id).instantiate_identity();
969                    let ty = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
970                    wfcx.register_wf_obligation(span, loc, ty.into());
971                }
972                Ok(())
973            }
974        }
975    })
976}
977
978/// In a type definition, we check that to ensure that the types of the fields are well-formed.
979pub(crate) fn check_type_defn<'tcx>(
980    tcx: TyCtxt<'tcx>,
981    item: LocalDefId,
982    all_sized: bool,
983) -> Result<(), ErrorGuaranteed> {
984    tcx.ensure_ok().check_representability(item);
985    let adt_def = tcx.adt_def(item);
986
987    enter_wf_checking_ctxt(tcx, item, |wfcx| {
988        let variants = adt_def.variants();
989        let packed = adt_def.repr().packed();
990        let own_params_require_monomorphization =
991            tcx.generics_of(item).own_requires_monomorphization();
992
993        for variant in variants.iter() {
994            // All field types must be well-formed.
995            for field in &variant.fields {
996                if let Some(def_id) = field.value {
997                    if !own_params_require_monomorphization {
998                        let _ = tcx.const_eval_poly(def_id);
999                    } else if tcx.features().default_field_values()
1000                        && let Some(local_def_id) = def_id.as_local()
1001                    {
1002                        // Do not redundantly trigger lint if the feature is not actually available.
1003
1004                        // We use the callsite span for default values that are actually macro calls
1005                        // into other crates, like for example `field: () = panic!(),`.
1006                        let field_span = tcx.def_span(def_id).source_callsite();
1007                        let mut multispan: MultiSpan = field_span.into();
1008                        multispan
1009                            .push_span_label(field_span, "this can't be const-evaluated until use");
1010                        let struct_start = tcx.def_span(item).shrink_to_lo();
1011                        multispan.push_span_context(tcx.def_span(field.did));
1012                        multispan.push_span_context(struct_start);
1013                        tcx.emit_node_span_lint(
1014                            UNEVALUATED_DEFAULT_FIELD_VALUE,
1015                            tcx.local_def_id_to_hir_id(local_def_id),
1016                            multispan,
1017                            UnevaluatedDefaultFieldValue {
1018                                field: field.name,
1019                                ty: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(item) }with_no_trimmed_paths!(tcx.def_path_str(item)),
1020                                padding: tcx
1021                                    .sess
1022                                    .source_map()
1023                                    .indentation_before(struct_start)
1024                                    .unwrap_or_default(),
1025                                struct_start,
1026                            },
1027                        );
1028                    }
1029                }
1030                let field_id = field.did.expect_local();
1031                let span = tcx.ty_span(field_id);
1032                let ty = wfcx.deeply_normalize(
1033                    span,
1034                    WellFormedLoc::None,
1035                    tcx.type_of(field.did).instantiate_identity(),
1036                );
1037                wfcx.register_wf_obligation(span, WellFormedLoc::Ty(field_id), ty.into());
1038
1039                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())
1040                    && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
    Some(ScalableElt::Container) => true,
    _ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1041                {
1042                    // Scalable vectors can only be fields of structs if the type has a
1043                    // `rustc_scalable_vector` attribute w/out specifying an element count
1044                    tcx.dcx().span_err(
1045                        span,
1046                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
                adt_def.variant_descr()))
    })format!(
1047                            "scalable vectors cannot be fields of a {}",
1048                            adt_def.variant_descr()
1049                        ),
1050                    );
1051                }
1052            }
1053
1054            // For DST, or when drop needs to copy things around, all
1055            // intermediate types must be sized.
1056            let needs_drop_copy = || {
1057                packed && {
1058                    let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1059                    let ty = tcx.erase_and_anonymize_regions(ty);
1060                    if !!ty.has_infer() {
    ::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1061                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1062                }
1063            };
1064            // All fields (except for possibly the last) should be sized.
1065            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1066            let unsized_len = if all_sized { 0 } else { 1 };
1067            for (idx, field) in
1068                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1069            {
1070                let last = idx == variant.fields.len() - 1;
1071                let span = tcx.ty_span(field.did.expect_local());
1072                let ty = wfcx.normalize(
1073                    span,
1074                    WellFormedLoc::None,
1075                    tcx.type_of(field.did).instantiate_identity(),
1076                );
1077                wfcx.register_bound(
1078                    traits::ObligationCause::new(
1079                        span,
1080                        wfcx.body_def_id,
1081                        ObligationCauseCode::FieldSized {
1082                            adt_kind: adt_def.adt_kind(),
1083                            span,
1084                            last,
1085                        },
1086                    ),
1087                    wfcx.param_env,
1088                    ty,
1089                    tcx.require_lang_item(LangItem::Sized, span),
1090                );
1091            }
1092
1093            // Explicit `enum` discriminant values must const-evaluate successfully.
1094            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1095                match tcx.const_eval_poly(discr_def_id) {
1096                    Ok(_) => {}
1097                    Err(ErrorHandled::Reported(..)) => {}
1098                    Err(ErrorHandled::TooGeneric(sp)) => {
1099                        ::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")
1100                    }
1101                }
1102            }
1103        }
1104
1105        check_where_clauses(wfcx, item);
1106        Ok(())
1107    })
1108}
1109
1110{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1110u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
                return Ok(());
            }
            let trait_def = tcx.trait_def(def_id);
            if trait_def.is_marker ||
                    #[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
                        {
                        TraitSpecializationKind::Marker => true,
                        _ => false,
                    } {
                for associated_def_id in &*tcx.associated_item_def_ids(def_id)
                    {
                    {
                            tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
                                        })).with_code(E0714)
                        }.emit();
                }
            }
            let res =
                enter_wf_checking_ctxt(tcx, def_id,
                    |wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
            res
        }
    }
}#[instrument(skip(tcx))]
1111pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1112    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1113        // `PointeeSized` is removed during lowering.
1114        return Ok(());
1115    }
1116
1117    let trait_def = tcx.trait_def(def_id);
1118    if trait_def.is_marker
1119        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1120    {
1121        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1122            struct_span_code_err!(
1123                tcx.dcx(),
1124                tcx.def_span(*associated_def_id),
1125                E0714,
1126                "marker traits cannot have associated items",
1127            )
1128            .emit();
1129        }
1130    }
1131
1132    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1133        check_where_clauses(wfcx, def_id);
1134        Ok(())
1135    });
1136
1137    res
1138}
1139
1140/// Checks all associated type defaults of trait `trait_def_id`.
1141///
1142/// Assuming the defaults are used, check that all predicates (bounds on the
1143/// assoc type and where clauses on the trait) hold.
1144fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1145    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1146
1147    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1147",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1147u32),
                        ::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);
1148    let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1149        |(bound, bound_span)| {
1150            traits::wf::clause_obligations(
1151                wfcx.infcx,
1152                wfcx.param_env,
1153                wfcx.body_def_id,
1154                bound,
1155                bound_span,
1156            )
1157        },
1158    );
1159
1160    wfcx.register_obligations(wf_obligations);
1161}
1162
1163fn check_item_fn(
1164    tcx: TyCtxt<'_>,
1165    def_id: LocalDefId,
1166    decl: &hir::FnDecl<'_>,
1167) -> Result<(), ErrorGuaranteed> {
1168    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1169        check_eiis_fn(tcx, def_id);
1170
1171        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1172        check_fn_or_method(wfcx, sig, decl, def_id);
1173        Ok(())
1174    })
1175}
1176
1177fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1178    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1179    // that was used to mark the implementation. This is a two step process.
1180    if let Some(EiiImpl { resolution, span, .. }) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
                        break 'done Some(&**i);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1181        let (foreign_item, name) = match resolution {
1182            EiiImplResolution::Macro(def_id) => {
1183                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1184                // signature that we'd like to compare the function we're currently checking with
1185                if let Some(foreign_item) =
1186                    {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1187                {
1188                    (foreign_item, tcx.item_name(*def_id))
1189                } else {
1190                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1191                    return;
1192                }
1193            }
1194            EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1195            EiiImplResolution::Error(_eg) => return,
1196        };
1197
1198        let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1199    }
1200}
1201
1202fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1203    // does the function have an EiiImpl attribute? that contains the defid of a *macro*
1204    // that was used to mark the implementation. This is a two step process.
1205    if let Some(EiiImpl { resolution, span, .. }) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
                        break 'done Some(&**i);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1206        let (foreign_item, name) = match resolution {
1207            EiiImplResolution::Macro(def_id) => {
1208                // we expect this macro to have the `EiiMacroFor` attribute, that points to a function
1209                // signature that we'd like to compare the function we're currently checking with
1210                if let Some(foreign_item) =
1211                    {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                        foreign_item: t, .. })) => {
                        break 'done Some(*t);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1212                {
1213                    (foreign_item, tcx.item_name(*def_id))
1214                } else {
1215                    tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1216                    return;
1217                }
1218            }
1219            EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1220            EiiImplResolution::Error(_eg) => return,
1221        };
1222
1223        let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1224    }
1225}
1226
1227{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1227u32),
                                    ::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))]
1228pub(crate) fn check_static_item<'tcx>(
1229    tcx: TyCtxt<'tcx>,
1230    item_id: LocalDefId,
1231    ty: Ty<'tcx>,
1232    should_check_for_sync: bool,
1233) -> Result<(), ErrorGuaranteed> {
1234    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1235        if should_check_for_sync {
1236            check_eiis_static(tcx, item_id, ty);
1237        }
1238
1239        let span = tcx.ty_span(item_id);
1240        let loc = WellFormedLoc::Ty(item_id);
1241        let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1242
1243        let is_foreign_item = tcx.is_foreign_item(item_id);
1244        let is_structurally_foreign_item = || {
1245            let tail = tcx.struct_tail_raw(
1246                item_ty,
1247                &ObligationCause::dummy(),
1248                |ty| wfcx.deeply_normalize(span, loc, ty),
1249                || {},
1250            );
1251
1252            matches!(tail.kind(), ty::Foreign(_))
1253        };
1254        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1255
1256        wfcx.register_wf_obligation(span, WellFormedLoc::Ty(item_id), item_ty.into());
1257        if forbid_unsized {
1258            let span = tcx.def_span(item_id);
1259            wfcx.register_bound(
1260                traits::ObligationCause::new(
1261                    span,
1262                    wfcx.body_def_id,
1263                    ObligationCauseCode::SizedConstOrStatic,
1264                ),
1265                wfcx.param_env,
1266                item_ty,
1267                tcx.require_lang_item(LangItem::Sized, span),
1268            );
1269        }
1270
1271        // Ensure that the end result is `Sync` in a non-thread local `static`.
1272        let should_check_for_sync = should_check_for_sync
1273            && !is_foreign_item
1274            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1275            && !tcx.is_thread_local_static(item_id.to_def_id());
1276
1277        if should_check_for_sync {
1278            wfcx.register_bound(
1279                traits::ObligationCause::new(
1280                    span,
1281                    wfcx.body_def_id,
1282                    ObligationCauseCode::SharedStatic,
1283                ),
1284                wfcx.param_env,
1285                item_ty,
1286                tcx.require_lang_item(LangItem::Sync, span),
1287            );
1288        }
1289        Ok(())
1290    })
1291}
1292
1293/// Runs checks common to both free consts and associated consts
1294{}
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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                ::tracing_core::__macro_support::Option::Some(1294u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("item_ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("item_ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                Result<(), ErrorGuaranteed> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let tcx = wfcx.tcx();
                        let span = tcx.def_span(def_id);
                        let mut res = Ok(());
                        if tcx.is_direct_const(def_id.into()) {
                            if !tcx.features().const_param_ty_unchecked() {
                                wfcx.register_bound(ObligationCause::new(span, def_id,
                                        ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
                                    item_ty,
                                    tcx.require_lang_item(LangItem::ConstParamTy, span));
                            }
                            if !tcx.features().generic_const_parameter_types() &&
                                    item_ty.has_param() {
                                res =
                                    Err(tcx.dcx().emit_err(ParamInTyOfConstParam {
                                                span,
                                                ty: item_ty,
                                            }));
                            }
                        }
                        if let Some(direct_rhs) = tcx.const_of_item(def_id) {
                            let raw_ct = direct_rhs.instantiate_identity();
                            let norm_ct =
                                wfcx.deeply_normalize(span, 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))));
                        }
                        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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1294",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1294u32),
                        ::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)]
1295pub(super) fn check_const_item<'tcx>(
1296    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1297    def_id: LocalDefId,
1298    item_ty: Ty<'tcx>,
1299) -> Result<(), ErrorGuaranteed> {
1300    let tcx = wfcx.tcx();
1301    let span = tcx.def_span(def_id);
1302
1303    let mut res = Ok(());
1304
1305    if tcx.is_direct_const(def_id.into()) {
1306        if !tcx.features().const_param_ty_unchecked() {
1307            wfcx.register_bound(
1308                ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1309                wfcx.param_env,
1310                item_ty,
1311                tcx.require_lang_item(LangItem::ConstParamTy, span),
1312            );
1313        }
1314        // FIXME(gca_min_const_items): We *might* want to move this check to `type_of`, so we can
1315        // return `ty::Error` if it references invalid params. However, doing so is hard, because
1316        // `type_of` doesn't know if it's a direct const - `const_of_item` determines that, and
1317        // `const_of_item` calls `type_of`.
1318        if !tcx.features().generic_const_parameter_types() && item_ty.has_param() {
1319            res = Err(tcx.dcx().emit_err(ParamInTyOfConstParam { span, ty: item_ty }));
1320        }
1321    }
1322
1323    if let Some(direct_rhs) = tcx.const_of_item(def_id) {
1324        let raw_ct = direct_rhs.instantiate_identity();
1325        let norm_ct = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), raw_ct);
1326        wfcx.register_wf_obligation(span, WellFormedLoc::Ty(def_id), norm_ct.into());
1327
1328        wfcx.register_obligation(Obligation::new(
1329            tcx,
1330            ObligationCause::new(
1331                span,
1332                def_id,
1333                ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id)),
1334            ),
1335            wfcx.param_env,
1336            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1337        ));
1338    }
1339
1340    res
1341}
1342
1343{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1343u32),
                                    ::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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1414",
                                                        "rustc_hir_analysis::check::wfcheck",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1414u32),
                                                        ::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_))]
1344fn check_impl<'tcx>(
1345    tcx: TyCtxt<'tcx>,
1346    item: &'tcx hir::Item<'tcx>,
1347    impl_: &hir::Impl<'_>,
1348) -> Result<(), ErrorGuaranteed> {
1349    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1350        match impl_.of_trait {
1351            Some(of_trait) => {
1352                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1353                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in
1354                // case other `Foo` impls are incoherent.
1355                tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1356                let trait_span = of_trait.trait_ref.path.span;
1357                let trait_ref = wfcx.deeply_normalize(
1358                    trait_span,
1359                    WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1360                    trait_ref,
1361                );
1362                let trait_pred =
1363                    ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive };
1364                let mut obligations = traits::wf::trait_obligations(
1365                    wfcx.infcx,
1366                    wfcx.param_env,
1367                    wfcx.body_def_id,
1368                    trait_pred,
1369                    trait_span,
1370                    item,
1371                );
1372                for obligation in &mut obligations {
1373                    if obligation.cause.span != trait_span {
1374                        // We already have a better span.
1375                        continue;
1376                    }
1377                    if let Some(pred) = obligation.predicate.as_trait_clause()
1378                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1379                    {
1380                        obligation.cause.span = impl_.self_ty.span;
1381                    }
1382                    if let Some(pred) = obligation.predicate.as_projection_clause()
1383                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1384                    {
1385                        obligation.cause.span = impl_.self_ty.span;
1386                    }
1387                }
1388
1389                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1390                if tcx.is_conditionally_const(item.owner_id.def_id) {
1391                    for (bound, _) in
1392                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1393                    {
1394                        let bound = wfcx.normalize(
1395                            item.span,
1396                            WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1397                            bound,
1398                        );
1399                        wfcx.register_obligation(Obligation::new(
1400                            tcx,
1401                            ObligationCause::new(
1402                                impl_.self_ty.span,
1403                                wfcx.body_def_id,
1404                                ObligationCauseCode::WellFormed(WellFormedLoc::HirId(
1405                                    of_trait.trait_ref.hir_ref_id,
1406                                )),
1407                            ),
1408                            wfcx.param_env,
1409                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1410                        ))
1411                    }
1412                }
1413
1414                debug!(?obligations);
1415                wfcx.register_obligations(obligations);
1416            }
1417            None => {
1418                let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1419                let self_ty = wfcx.deeply_normalize(
1420                    item.span,
1421                    WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1422                    Unnormalized::new_wip(self_ty),
1423                );
1424                wfcx.register_wf_obligation(
1425                    impl_.self_ty.span,
1426                    WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1427                    self_ty.into(),
1428                );
1429            }
1430        }
1431
1432        check_where_clauses(wfcx, item.owner_id.def_id);
1433        Ok(())
1434    })
1435}
1436
1437/// Checks where-clauses and inline bounds that are declared on `def_id`.
1438{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1438u32),
                                    ::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::panic("internal error: entered unreachable code"),
                                ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
                                    continue,
                                ty::ConstKind::Value(cv) => cv.ty,
                                ty::ConstKind::Alias(_, alias_const) => {
                                    alias_const.type_of(infcx.tcx).skip_norm_wip()
                                }
                                ty::ConstKind::Param(param_ct) => {
                                    param_ct.find_const_ty_from_env(wfcx.param_env)
                                }
                            };
                        let param_ty =
                            tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
                        if !ct_ty.has_param() && !param_ty.has_param() {
                            let cause =
                                traits::ObligationCause::new(tcx.def_span(param.def_id),
                                    wfcx.body_def_id,
                                    ObligationCauseCode::WellFormed(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))]
1439pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1440    let infcx = wfcx.infcx;
1441    let tcx = wfcx.tcx();
1442
1443    let gen_clauses = tcx.clauses_of(def_id.to_def_id());
1444    let generics = tcx.generics_of(def_id);
1445
1446    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1447    // For example, this forbids the declaration:
1448    //
1449    //     struct Foo<T = Vec<[u32]>> { .. }
1450    //
1451    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1452    for param in &generics.own_params {
1453        if let Some(default) = param
1454            .default_value(tcx)
1455            .map(ty::EarlyBinder::instantiate_identity)
1456            .map(Unnormalized::skip_norm_wip)
1457        {
1458            // Ignore dependent defaults -- that is, where the default of one type
1459            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1460            // be sure if it will error or not as user might always specify the other.
1461            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1462            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1463            // eagerly error but we don't as we have `ConstKind::Alias(.., [N, M])`.
1464            if !default.has_param() {
1465                wfcx.register_wf_obligation(
1466                    tcx.def_span(param.def_id),
1467                    matches!(param.kind, GenericParamDefKind::Type { .. })
1468                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local()))
1469                        .unwrap_or(WellFormedLoc::None),
1470                    default.as_term().unwrap(),
1471                );
1472            } else {
1473                // If we've got a generic const parameter we still want to check its
1474                // type is correct in case both it and the param type are fully concrete.
1475                let GenericArgKind::Const(ct) = default.kind() else {
1476                    continue;
1477                };
1478
1479                let ct_ty = match ct.kind() {
1480                    ty::ConstKind::Infer(_)
1481                    | ty::ConstKind::Placeholder(_)
1482                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1483                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1484                    ty::ConstKind::Value(cv) => cv.ty,
1485                    ty::ConstKind::Alias(_, alias_const) => {
1486                        alias_const.type_of(infcx.tcx).skip_norm_wip()
1487                    }
1488                    ty::ConstKind::Param(param_ct) => {
1489                        param_ct.find_const_ty_from_env(wfcx.param_env)
1490                    }
1491                };
1492
1493                let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1494                if !ct_ty.has_param() && !param_ty.has_param() {
1495                    let cause = traits::ObligationCause::new(
1496                        tcx.def_span(param.def_id),
1497                        wfcx.body_def_id,
1498                        ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id)),
1499                    );
1500                    wfcx.register_obligation(Obligation::new(
1501                        tcx,
1502                        cause,
1503                        wfcx.param_env,
1504                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1505                    ));
1506                }
1507            }
1508        }
1509    }
1510
1511    // Check that trait clauses are WF when params are instantiated with their defaults.
1512    // We don't want to overly constrain the clauses that may be written but we want to
1513    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1514    // Therefore we check if a clause which contains a single type param
1515    // with a concrete default is WF with that default instantiated.
1516    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1517    //
1518    // First we build the defaulted generic parameters.
1519    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1520        if param.index >= generics.parent_count as u32
1521            // If the param has a default, ...
1522            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1523            // ... and it's not a dependent default, ...
1524            && !default.has_param()
1525        {
1526            // ... then instantiate it with the default.
1527            return default;
1528        }
1529        tcx.mk_param_from_def(param)
1530    });
1531
1532    // Now we build the instantiated clauses.
1533    let default_obligations = gen_clauses
1534        .clauses
1535        .iter()
1536        .flat_map(|&(clause, sp)| {
1537            #[derive(Default)]
1538            struct CountParams {
1539                params: FxHashSet<u32>,
1540            }
1541            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1542                type Result = ControlFlow<()>;
1543                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1544                    if let ty::Param(param) = t.kind() {
1545                        self.params.insert(param.index);
1546                    }
1547                    t.super_visit_with(self)
1548                }
1549
1550                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1551                    ControlFlow::Break(())
1552                }
1553
1554                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1555                    if let ty::ConstKind::Param(param) = c.kind() {
1556                        self.params.insert(param.index);
1557                    }
1558                    c.super_visit_with(self)
1559                }
1560            }
1561            let mut param_count = CountParams::default();
1562            let has_region = clause.visit_with(&mut param_count).is_break();
1563            let instantiated_clause = ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
1564            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1565            // or clauses with multiple params.
1566            if instantiated_clause.skip_normalization().has_non_region_param()
1567                || param_count.params.len() > 1
1568                || has_region
1569            {
1570                None
1571            } else if gen_clauses
1572                .clauses
1573                .iter()
1574                .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_clause)
1575            {
1576                // Avoid duplication of clauses that contain no parameters, for example.
1577                None
1578            } else {
1579                Some((instantiated_clause, sp))
1580            }
1581        })
1582        .map(|(clause, sp)| {
1583            // Convert each of those into an obligation. So if you have
1584            // something like `struct Foo<T: Copy = String>`, we would
1585            // take that clause `T: Copy`, instantiated with `String: Copy`
1586            // (actually that happens in the previous `flat_map` call),
1587            // and then try to prove it (in this case, we'll fail).
1588            //
1589            // Note the subtle difference from how we handle `gen_clauses`
1590            // below: there, we are not trying to prove those clauses
1591            // to be *true* but merely *well-formed*.
1592            let clause = wfcx.normalize(sp, WellFormedLoc::None, clause);
1593            let cause = traits::ObligationCause::new(
1594                sp,
1595                wfcx.body_def_id,
1596                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1597            );
1598            Obligation::new(tcx, cause, wfcx.param_env, clause)
1599        });
1600
1601    let gen_clauses = gen_clauses.instantiate_identity(tcx);
1602
1603    let assoc_const_obligations: Vec<_> = gen_clauses
1604        .clauses
1605        .iter()
1606        .copied()
1607        .zip(gen_clauses.spans.iter().copied())
1608        .filter_map(|(clause, sp)| {
1609            let clause = clause.skip_norm_wip();
1610            let proj = clause.as_projection_clause()?;
1611            let pred_binder = proj
1612                .map_bound(|pred| {
1613                    pred.term.as_const().map(|ct| {
1614                        let assoc_const_ty =
1615                            pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1616                        ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1617                    })
1618                })
1619                .transpose();
1620            pred_binder.map(|pred_binder| {
1621                let cause = traits::ObligationCause::new(
1622                    sp,
1623                    wfcx.body_def_id,
1624                    ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1625                );
1626                Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1627            })
1628        })
1629        .collect();
1630
1631    assert_eq!(gen_clauses.clauses.len(), gen_clauses.spans.len());
1632    let wf_obligations = gen_clauses.into_iter().flat_map(|(p, sp)| {
1633        traits::wf::clause_obligations(
1634            infcx,
1635            wfcx.param_env,
1636            wfcx.body_def_id,
1637            p.skip_norm_wip(),
1638            sp,
1639        )
1640    });
1641    let obligations: Vec<_> =
1642        wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1643    wfcx.register_obligations(obligations);
1644}
1645
1646{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1646u32),
                                    ::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))]
1647fn check_fn_or_method<'tcx>(
1648    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1649    sig: ty::PolyFnSig<'tcx>,
1650    hir_decl: &hir::FnDecl<'_>,
1651    def_id: LocalDefId,
1652) {
1653    let tcx = wfcx.tcx();
1654    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1655
1656    // Normalize the input and output types one at a time, using a different
1657    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1658    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1659    // for each type, preventing the HIR wf check from generating
1660    // a nice error message.
1661    let arg_span =
1662        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1663
1664    sig.inputs_and_output =
1665        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1666            wfcx.deeply_normalize(
1667                arg_span(idx),
1668                WellFormedLoc::Param {
1669                    function: def_id,
1670                    // Note that the `param_idx` of the output type is
1671                    // one greater than the index of the last input type.
1672                    param_idx: idx,
1673                },
1674                Unnormalized::new_wip(ty),
1675            )
1676        }));
1677
1678    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1679        wfcx.register_wf_obligation(
1680            arg_span(idx),
1681            WellFormedLoc::Param { function: def_id, param_idx: idx },
1682            ty.into(),
1683        );
1684    }
1685
1686    check_where_clauses(wfcx, def_id);
1687
1688    if sig.abi() == ExternAbi::RustCall {
1689        let span = tcx.def_span(def_id);
1690        let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1691        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1692        // Check that the argument is a tuple and is sized
1693        if let Some(ty) = inputs.next() {
1694            wfcx.register_bound(
1695                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1696                wfcx.param_env,
1697                *ty,
1698                tcx.require_lang_item(LangItem::Tuple, span),
1699            );
1700            wfcx.register_bound(
1701                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1702                wfcx.param_env,
1703                *ty,
1704                tcx.require_lang_item(LangItem::Sized, span),
1705            );
1706        } else {
1707            tcx.dcx().span_err(
1708                hir_decl.inputs.last().map_or(span, |input| input.span),
1709                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1710            );
1711        }
1712        // No more inputs other than the `self` type and the tuple type
1713        if inputs.next().is_some() {
1714            tcx.dcx().span_err(
1715                hir_decl.inputs.last().map_or(span, |input| input.span),
1716                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1717            );
1718        }
1719    }
1720
1721    // If the function has a body, additionally require that the return type is sized.
1722    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1723        let span = match hir_decl.output {
1724            hir::FnRetTy::Return(ty) => ty.span,
1725            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1726        };
1727
1728        wfcx.register_bound(
1729            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1730            wfcx.param_env,
1731            sig.output(),
1732            tcx.require_lang_item(LangItem::Sized, span),
1733        );
1734    }
1735}
1736
1737/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1738#[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)]
1739enum ArbitrarySelfTypesLevel {
1740    Basic,        // just arbitrary_self_types
1741    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1742}
1743
1744{}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1744u32),
                                    ::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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1764",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1764u32),
                                    ::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))]
1745fn check_method_receiver<'tcx>(
1746    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1747    fn_sig: &hir::FnSig<'_>,
1748    method: ty::AssocItem,
1749    self_ty: Ty<'tcx>,
1750) -> Result<(), ErrorGuaranteed> {
1751    let tcx = wfcx.tcx();
1752
1753    if !method.is_method() {
1754        return Ok(());
1755    }
1756
1757    let span = fn_sig.decl.inputs[0].span;
1758    let loc = WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 };
1759
1760    let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1761    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1762    let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1763
1764    debug!("check_method_receiver: sig={:?}", sig);
1765
1766    let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1767
1768    let receiver_ty = sig.inputs()[0];
1769    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1770
1771    // If the receiver already has errors reported, consider it valid to avoid
1772    // unnecessary errors (#58712).
1773    receiver_ty.error_reported()?;
1774
1775    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1776        Some(ArbitrarySelfTypesLevel::WithPointers)
1777    } else if tcx.features().arbitrary_self_types() {
1778        Some(ArbitrarySelfTypesLevel::Basic)
1779    } else {
1780        None
1781    };
1782    let generics = tcx.generics_of(method.def_id);
1783
1784    let receiver_validity =
1785        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1786    if let Err(receiver_validity_err) = receiver_validity {
1787        return Err(match arbitrary_self_types_level {
1788            // Wherever possible, emit a message advising folks that the features
1789            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1790            // have helped.
1791            None if receiver_is_valid(
1792                wfcx,
1793                span,
1794                receiver_ty,
1795                self_ty,
1796                Some(ArbitrarySelfTypesLevel::Basic),
1797                generics,
1798            )
1799            .is_ok() =>
1800            {
1801                // Report error; would have worked with `arbitrary_self_types`.
1802                feature_err(
1803                    &tcx.sess,
1804                    sym::arbitrary_self_types,
1805                    span,
1806                    format!(
1807                        "`{receiver_ty}` cannot be used as the type of `self` without \
1808                            the `arbitrary_self_types` feature",
1809                    ),
1810                )
1811                .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>`"))
1812                .emit_err()
1813            }
1814            None | Some(ArbitrarySelfTypesLevel::Basic)
1815                if receiver_is_valid(
1816                    wfcx,
1817                    span,
1818                    receiver_ty,
1819                    self_ty,
1820                    Some(ArbitrarySelfTypesLevel::WithPointers),
1821                    generics,
1822                )
1823                .is_ok() =>
1824            {
1825                // Report error; would have worked with `arbitrary_self_types_pointers`.
1826                feature_err(
1827                    &tcx.sess,
1828                    sym::arbitrary_self_types_pointers,
1829                    span,
1830                    format!(
1831                        "`{receiver_ty}` cannot be used as the type of `self` without \
1832                            the `arbitrary_self_types_pointers` feature",
1833                    ),
1834                )
1835                .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1836                .emit_err()
1837            }
1838            _ =>
1839            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1840            {
1841                match receiver_validity_err {
1842                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1843                        let adt_def =
1844                            receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
1845
1846                        let hint = match adt_def {
1847                            Some(adt) => {
1848                                if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
1849                                    Some(InvalidReceiverTyHint::NonNull)
1850                                } else {
1851                                    match tcx.get_diagnostic_name(adt.did()) {
1852                                        Some(sym::RcWeak | sym::ArcWeak) => {
1853                                            Some(InvalidReceiverTyHint::Weak)
1854                                        }
1855                                        _ => None,
1856                                    }
1857                                }
1858                            }
1859                            _ => None,
1860                        };
1861
1862                        tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1863                            span,
1864                            receiver_ty,
1865                            hint,
1866                        })
1867                    }
1868                    ReceiverValidityError::DoesNotDeref => {
1869                        tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1870                            span,
1871                            receiver_ty,
1872                        })
1873                    }
1874                    ReceiverValidityError::MethodGenericParamUsed => tcx
1875                        .dcx()
1876                        .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
1877                }
1878            }
1879        });
1880    }
1881    Ok(())
1882}
1883
1884/// Error cases which may be returned from `receiver_is_valid`. These error
1885/// cases are generated in this function as they may be unearthed as we explore
1886/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1887enum ReceiverValidityError {
1888    /// The self type does not get to the receiver type by following the
1889    /// autoderef chain.
1890    DoesNotDeref,
1891    /// A type was found which is a method type parameter, and that's not allowed.
1892    MethodGenericParamUsed,
1893}
1894
1895/// Confirms that a type is not a type parameter referring to one of the
1896/// method's type params.
1897fn confirm_type_is_not_a_method_generic_param(
1898    ty: Ty<'_>,
1899    method_generics: &ty::Generics,
1900) -> Result<(), ReceiverValidityError> {
1901    if let ty::Param(param) = ty.kind() {
1902        if (param.index as usize) >= method_generics.parent_count {
1903            return Err(ReceiverValidityError::MethodGenericParamUsed);
1904        }
1905    }
1906    Ok(())
1907}
1908
1909/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1910/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1911/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1912/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1913/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1914///
1915/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1916/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1917/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1918fn receiver_is_valid<'tcx>(
1919    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1920    span: Span,
1921    receiver_ty: Ty<'tcx>,
1922    self_ty: Ty<'tcx>,
1923    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1924    method_generics: &ty::Generics,
1925) -> Result<(), ReceiverValidityError> {
1926    let infcx = wfcx.infcx;
1927    let tcx = wfcx.tcx();
1928    let cause =
1929        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1930
1931    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1932    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1933        let ocx = ObligationCtxt::new(wfcx.infcx);
1934        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1935        if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1936            Ok(())
1937        } else {
1938            Err(NoSolution)
1939        }
1940    }) {
1941        return Ok(());
1942    }
1943
1944    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1945
1946    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1947
1948    // The `arbitrary_self_types` feature allows custom smart pointer
1949    // types to be method receivers, as identified by following the Receiver<Target=T>
1950    // chain.
1951    if arbitrary_self_types_enabled.is_some() {
1952        autoderef = autoderef.use_receiver_trait();
1953    }
1954
1955    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1956    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1957        autoderef = autoderef.include_raw_pointers();
1958    }
1959
1960    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1961    while let Some((potential_self_ty, _)) = autoderef.next() {
1962        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1962",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(1962u32),
                        ::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!(
1963            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1964            potential_self_ty, self_ty
1965        );
1966
1967        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1968
1969        // Check if the self type unifies. If it does, then commit the result
1970        // since it may have region side-effects.
1971        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1972            let ocx = ObligationCtxt::new(wfcx.infcx);
1973            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1974            if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1975                Ok(())
1976            } else {
1977                Err(NoSolution)
1978            }
1979        }) {
1980            wfcx.register_obligations(autoderef.into_obligations());
1981            return Ok(());
1982        }
1983
1984        // Without `feature(arbitrary_self_types)`, we require that each step in the
1985        // deref chain implement `LegacyReceiver`.
1986        if arbitrary_self_types_enabled.is_none() {
1987            let legacy_receiver_trait_def_id =
1988                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1989            if !legacy_receiver_is_implemented(
1990                wfcx,
1991                legacy_receiver_trait_def_id,
1992                cause.clone(),
1993                potential_self_ty,
1994            ) {
1995                // We cannot proceed.
1996                break;
1997            }
1998
1999            // Register the bound, in case it has any region side-effects.
2000            wfcx.register_bound(
2001                cause.clone(),
2002                wfcx.param_env,
2003                potential_self_ty,
2004                legacy_receiver_trait_def_id,
2005            );
2006        }
2007    }
2008
2009    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:2009",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(2009u32),
                        ::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);
2010    Err(ReceiverValidityError::DoesNotDeref)
2011}
2012
2013fn legacy_receiver_is_implemented<'tcx>(
2014    wfcx: &WfCheckingCtxt<'_, 'tcx>,
2015    legacy_receiver_trait_def_id: DefId,
2016    cause: ObligationCause<'tcx>,
2017    receiver_ty: Ty<'tcx>,
2018) -> bool {
2019    let tcx = wfcx.tcx();
2020    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2021
2022    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2023
2024    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2025        true
2026    } else {
2027        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs:2027",
                        "rustc_hir_analysis::check::wfcheck",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                        ::tracing_core::__macro_support::Option::Some(2027u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __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!(
2028            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2029            receiver_ty
2030        );
2031        false
2032    }
2033}
2034
2035pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2036    match tcx.def_kind(def_id) {
2037        DefKind::Enum | DefKind::Struct | DefKind::Union => {
2038            // Ok
2039        }
2040        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:?}"),
2041    }
2042
2043    let ty_clauses = tcx.clauses_of(def_id);
2044    {
    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);
2045    let variances = tcx.variances_of(def_id);
2046
2047    let mut constrained_parameters: FxHashSet<_> = variances
2048        .iter()
2049        .enumerate()
2050        .filter(|&(_, &variance)| variance != ty::Bivariant)
2051        .map(|(index, _)| Parameter(index as u32))
2052        .collect();
2053
2054    identify_constrained_generic_params(tcx, ty_clauses, None, &mut constrained_parameters);
2055
2056    // Lazily calculated because it is only needed in case of an error.
2057    let explicitly_bounded_params = LazyCell::new(|| {
2058        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2059        tcx.hir_node_by_def_id(def_id)
2060            .generics()
2061            .unwrap()
2062            .predicates
2063            .iter()
2064            .filter_map(|predicate| match predicate.kind {
2065                hir::WherePredicateKind::BoundPredicate(predicate) => {
2066                    match icx.lower_ty(predicate.bounded_ty).kind() {
2067                        ty::Param(data) => Some(Parameter(data.index)),
2068                        _ => None,
2069                    }
2070                }
2071                _ => None,
2072            })
2073            .collect::<FxHashSet<_>>()
2074    });
2075
2076    for (index, _) in variances.iter().enumerate() {
2077        let parameter = Parameter(index as u32);
2078
2079        if constrained_parameters.contains(&parameter) {
2080            continue;
2081        }
2082
2083        let node = tcx.hir_node_by_def_id(def_id);
2084        let item = node.expect_item();
2085        let hir_generics = node.generics().unwrap();
2086        let hir_param = &hir_generics.params[index];
2087
2088        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2089
2090        if ty_param.def_id != hir_param.def_id.into() {
2091            // Valid programs always have lifetimes before types in the generic parameter list.
2092            // ty_generics are normalized to be in this required order, and variances are built
2093            // from ty generics, not from hir generics. but we need hir generics to get
2094            // a span out.
2095            //
2096            // If they aren't in the same order, then the user has written invalid code, and already
2097            // got an error about it (or I'm wrong about this).
2098            tcx.dcx().span_delayed_bug(
2099                hir_param.span,
2100                "hir generics and ty generics in different order",
2101            );
2102            continue;
2103        }
2104
2105        // Look for `ErrorGuaranteed` deeply within this type.
2106        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2107            .type_of(def_id)
2108            .instantiate_identity()
2109            .skip_norm_wip()
2110            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2111        {
2112            continue;
2113        }
2114
2115        match hir_param.name {
2116            hir::ParamName::Error(_) => {
2117                // Don't report a bivariance error for a lifetime that isn't
2118                // even valid to name.
2119            }
2120            _ => {
2121                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2122                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2123            }
2124        }
2125    }
2126}
2127
2128/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2129struct HasErrorDeep<'tcx> {
2130    tcx: TyCtxt<'tcx>,
2131    seen: FxHashSet<DefId>,
2132}
2133impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2134    type Result = ControlFlow<ErrorGuaranteed>;
2135
2136    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2137        match *ty.kind() {
2138            ty::Adt(def, _) => {
2139                if self.seen.insert(def.did()) {
2140                    for field in def.all_fields() {
2141                        self.tcx
2142                            .type_of(field.did)
2143                            .instantiate_identity()
2144                            .skip_norm_wip()
2145                            .visit_with(self)?;
2146                    }
2147                }
2148            }
2149            ty::Error(guar) => return ControlFlow::Break(guar),
2150            _ => {}
2151        }
2152        ty.super_visit_with(self)
2153    }
2154
2155    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2156        if let Err(guar) = r.error_reported() {
2157            ControlFlow::Break(guar)
2158        } else {
2159            ControlFlow::Continue(())
2160        }
2161    }
2162
2163    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2164        if let Err(guar) = c.error_reported() {
2165            ControlFlow::Break(guar)
2166        } else {
2167            ControlFlow::Continue(())
2168        }
2169    }
2170}
2171
2172fn report_bivariance<'tcx>(
2173    tcx: TyCtxt<'tcx>,
2174    param: &'tcx hir::GenericParam<'tcx>,
2175    has_explicit_bounds: bool,
2176    item: &'tcx hir::Item<'tcx>,
2177) -> ErrorGuaranteed {
2178    let param_name = param.name.ident();
2179
2180    let help = match item.kind {
2181        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2182            if let Some(def_id) = tcx.lang_items().phantom_data() {
2183                diagnostics::UnusedGenericParameterHelp::Adt {
2184                    param_name,
2185                    phantom_data: tcx.def_path_str(def_id),
2186                }
2187            } else {
2188                diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2189            }
2190        }
2191        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:?}"),
2192    };
2193
2194    let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2195    intravisit::walk_item(
2196        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2197        item,
2198    );
2199
2200    if !usage_spans.is_empty() {
2201        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2202        // not actually looking into substitutions, just walking through fields / the "RHS".
2203        // We don't recurse into the hidden types of opaques or anything else fancy.
2204        let item_def_id = item.owner_id.to_def_id();
2205        let is_probably_cyclical =
2206            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2207                .visit_def(item_def_id)
2208                .is_break();
2209        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2210        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2211        // alias, and we should call those parameter usages recursive rather than just saying
2212        // they're unused...
2213        //
2214        // We currently report *all* of the parameter usages, since computing the exact
2215        // subset is very involved, and the fact we're mentioning recursion at all is
2216        // likely to guide the user in the right direction.
2217        if is_probably_cyclical {
2218            return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2219                spans: usage_spans,
2220                param_span: param.span,
2221                param_name,
2222                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2223                help,
2224                note: (),
2225            });
2226        }
2227    }
2228
2229    let const_param_help =
2230        #[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);
2231
2232    let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2233        span: param.span,
2234        param_name,
2235        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2236        usage_spans,
2237        help,
2238        const_param_help,
2239    });
2240    diag.code(E0392);
2241    if item.kind.recovered() {
2242        // Silence potentially redundant error, as the item had a parse error.
2243        diag.delay_as_bug()
2244    } else {
2245        diag.emit_err()
2246    }
2247}
2248
2249/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2250/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2251/// cyclical.
2252///
2253/// Notably, we don't consider substitutions here, so this may have false positives.
2254struct IsProbablyCyclical<'tcx> {
2255    tcx: TyCtxt<'tcx>,
2256    item_def_id: DefId,
2257    seen: FxHashSet<DefId>,
2258}
2259
2260impl<'tcx> IsProbablyCyclical<'tcx> {
2261    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2262        match self.tcx.def_kind(def_id) {
2263            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2264                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2265                    self.tcx
2266                        .type_of(field.did)
2267                        .instantiate_identity()
2268                        .skip_norm_wip()
2269                        .visit_with(self)
2270                })
2271            }
2272            _ => ControlFlow::Continue(()),
2273        }
2274    }
2275}
2276
2277impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2278    type Result = ControlFlow<(), ()>;
2279
2280    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2281        if let Some(adt_def) = ty.ty_adt_def() {
2282            if adt_def.did() == self.item_def_id {
2283                return ControlFlow::Break(());
2284            }
2285            if self.seen.insert(adt_def.did()) {
2286                self.visit_def(adt_def.did())?;
2287            }
2288        }
2289        ty.super_visit_with(self)
2290    }
2291}
2292
2293/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2294///
2295/// This is used to report places where the user has used parameters in a
2296/// non-variance-constraining way for better bivariance errors.
2297struct CollectUsageSpans<'a> {
2298    spans: &'a mut Vec<Span>,
2299    param_def_id: DefId,
2300}
2301
2302impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2303    type Result = ();
2304
2305    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2306        // Skip the generics. We only care about fields, not where clause/param bounds.
2307    }
2308
2309    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2310        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2311            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2312                && def_id == self.param_def_id
2313            {
2314                self.spans.push(t.span);
2315                return;
2316            } else if let Res::SelfTyAlias { .. } = qpath.res {
2317                self.spans.push(t.span);
2318                return;
2319            }
2320        }
2321        intravisit::walk_ty(self, t);
2322    }
2323}
2324
2325impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2326    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2327    /// aren't true.
2328    {}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2328u32),
                                    ::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))]
2329    fn check_false_global_bounds(&mut self) {
2330        let tcx = self.ocx.infcx.tcx;
2331        let mut span = tcx.def_span(self.body_def_id);
2332        let empty_env = ty::ParamEnv::empty();
2333
2334        let clauses_with_span = tcx.clauses_of(self.body_def_id).clauses.iter().copied();
2335        // Check elaborated bounds.
2336        let implied_obligations = traits::elaborate(tcx, clauses_with_span);
2337
2338        for (clause, obligation_span) in implied_obligations {
2339            match clause.kind().skip_binder() {
2340                // We lower empty bounds like `Vec<dyn Copy>:` as
2341                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2342                // regular WF checking
2343                ty::ClauseKind::WellFormed(..)
2344                // Unstable feature goals cannot be proven in an empty environment so skip them
2345                | ty::ClauseKind::UnstableFeature(..) => continue,
2346                _ => {}
2347            }
2348
2349            // Match the existing behavior.
2350            if clause.is_global() && !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2351                let clause =
2352                    self.normalize(span, WellFormedLoc::None, Unnormalized::new_wip(clause));
2353
2354                // only use the span of the predicate clause (#90869)
2355                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2356                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2357                    span = predicates
2358                        .iter()
2359                        // There seems to be no better way to find out which predicate we are in
2360                        .find(|pred| pred.span.contains(obligation_span))
2361                        .map(|pred| pred.span)
2362                        .unwrap_or(obligation_span);
2363                }
2364
2365                let obligation = Obligation::new(
2366                    tcx,
2367                    traits::ObligationCause::new(
2368                        span,
2369                        self.body_def_id,
2370                        ObligationCauseCode::TrivialBound,
2371                    ),
2372                    empty_env,
2373                    clause,
2374                );
2375                self.ocx.register_obligation(obligation);
2376            }
2377        }
2378    }
2379
2380    {}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2380u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("body")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("body");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let TestBinderBody { foralls, exists, constraints, predicates } =
                body;
            if !predicates.is_empty() {
                for (predicate, span) in predicates {
                    let cause =
                        traits::ObligationCause::misc(span, self.body_def_id);
                    let obligation =
                        Obligation::new(self.tcx(), cause, self.param_env,
                            predicate);
                    self.register_obligation(obligation);
                }
                match self.ocx.evaluate_obligations_error_on_ambiguity() {
                    TraitErrors::NoErrors => (),
                    TraitErrors::HasErrors(errors) => {
                        self.infcx.err_ctxt().report_fulfillment_errors(errors);
                        return;
                    }
                }
            }
            let constraints =
                match validate(self.tcx(), &constraints) {
                    Ok(()) => constraints,
                    Err(_guar) =>
                        ty::region_constraint::RegionConstraint::new_true(),
                };
            self.infcx.register_solver_region_constraint(constraints);
            for forall in foralls { self.check_test_binder_forall(forall); }
            for exists in exists { self.check_test_binder_exists(exists); }
            fn validate<'tcx>(tcx: TyCtxt<'tcx>,
                constraint: &SolverRegionConstraint<'tcx>)
                -> Result<(), ErrorGuaranteed> {
                let mut r = Ok(());
                let mut validate_and =
                    |and: &And<TyCtxt<'_>, _>|
                        {
                            for c in and.0.iter() {
                                match c {
                                    LeafRegionConstraint::Ambiguity(_) |
                                        LeafRegionConstraint::RegionOutlives(..) |
                                        LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (),
                                    LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) =>
                                        {
                                        if let ty::Placeholder(_) | ty::Param(_) = ty.kind()
                                            {} else {
                                            let mut err =
                                                tcx.dcx().struct_span_err(*span,
                                                    "the lhs of a ty outlives must be a placeholder");
                                            err.note(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("it is a {0}", ty))
                                                    }));
                                            err.note(::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("and here it is `Debug`ged :3 {0:?}",
                                                                ty))
                                                    }));
                                            r = Err(err.emit_err());
                                        }
                                    }
                                }
                            }
                        };
                validate_and(&constraint.and_constraint);
                for and in constraint.or_constraint.0.iter() {
                    validate_and(and);
                }
                r
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2381    pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {
2382        let TestBinderBody { foralls, exists, constraints, predicates } = body;
2383        if !predicates.is_empty() {
2384            for (predicate, span) in predicates {
2385                let cause = traits::ObligationCause::misc(span, self.body_def_id);
2386                let obligation = Obligation::new(self.tcx(), cause, self.param_env, predicate);
2387                self.register_obligation(obligation);
2388            }
2389            match self.ocx.evaluate_obligations_error_on_ambiguity() {
2390                TraitErrors::NoErrors => (),
2391                TraitErrors::HasErrors(errors) => {
2392                    self.infcx.err_ctxt().report_fulfillment_errors(errors);
2393                    return;
2394                }
2395            }
2396        }
2397
2398        let constraints = match validate(self.tcx(), &constraints) {
2399            Ok(()) => constraints,
2400            Err(_guar) => ty::region_constraint::RegionConstraint::new_true(),
2401        };
2402
2403        self.infcx.register_solver_region_constraint(constraints);
2404
2405        for forall in foralls {
2406            self.check_test_binder_forall(forall);
2407        }
2408        for exists in exists {
2409            self.check_test_binder_exists(exists);
2410        }
2411
2412        fn validate<'tcx>(
2413            tcx: TyCtxt<'tcx>,
2414            constraint: &SolverRegionConstraint<'tcx>,
2415        ) -> Result<(), ErrorGuaranteed> {
2416            let mut r = Ok(());
2417
2418            let mut validate_and = |and: &And<TyCtxt<'_>, _>| {
2419                for c in and.0.iter() {
2420                    match c {
2421                        LeafRegionConstraint::Ambiguity(_)
2422                        | LeafRegionConstraint::RegionOutlives(..)
2423                        | LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (), // OK
2424                        LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) => {
2425                            // we can't check this during lowering, because the ty is a ty::Bound that gets
2426                            // instantiated with a placeholder when entering the containing forall.
2427                            if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
2428                                // all OK
2429                            } else {
2430                                let mut err = tcx.dcx().struct_span_err(
2431                                    *span,
2432                                    "the lhs of a ty outlives must be a placeholder",
2433                                );
2434                                err.note(format!("it is a {ty}"));
2435                                err.note(format!("and here it is `Debug`ged :3 {ty:?}"));
2436                                r = Err(err.emit_err());
2437                            }
2438                        }
2439                    }
2440                }
2441            };
2442
2443            validate_and(&constraint.and_constraint);
2444            for and in constraint.or_constraint.0.iter() {
2445                validate_and(and);
2446            }
2447
2448            r
2449        }
2450    }
2451
2452    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_test_binder_forall",
                                    "rustc_hir_analysis::check::wfcheck",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2452u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("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 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))]
2453    fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {
2454        let prev_u = self.infcx.universe();
2455        self.infcx.enter_forall(forall.binder, |body| {
2456            let u = if prev_u == self.infcx.universe() {
2457                // `enter_forall` has some special cases to avoid creating universes
2458                // in some cases for perf reasons. Not creating the universe unconditionally
2459                // breaks calling `eagerly_handle_placeholders` later on in this function.
2460                //
2461                // See `test_infra_empty_forall.rs`.
2462                self.infcx.create_next_universe()
2463            } else {
2464                self.infcx.universe()
2465            };
2466
2467            let assumptions = self.build_test_binder_assumptions(
2468                forall.span,
2469                body.type_outlives,
2470                body.region_outlives,
2471            );
2472            self.infcx.insert_placeholder_assumptions(u, assumptions);
2473            self.check_test_binder_body(body.value);
2474            let solver_region_constraint = self.infcx.get_solver_region_constraint();
2475            let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(
2476                self.infcx,
2477                solver_region_constraint.without_spans(),
2478                u,
2479            )
2480            .with_spans(forall.span);
2481            if let Some(assert_on_exit) = &forall.assert_on_exit {
2482                self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);
2483            }
2484            self.infcx.overwrite_solver_region_constraint(constraint);
2485        });
2486    }
2487
2488    fn build_test_binder_assumptions(
2489        &self,
2490        span: Span,
2491        type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,
2492        region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,
2493    ) -> ty::region_constraint::Assumptions<TyCtxt<'tcx>> {
2494        for clause in &type_outlives {
2495            if !#[allow(non_exhaustive_omitted_patterns)] match clause.skip_binder().0.kind()
    {
    ty::Alias(..) | ty::Param(..) | ty::Placeholder(..) => true,
    _ => false,
}matches!(
2496                clause.skip_binder().0.kind(),
2497                ty::Alias(..) | ty::Param(..) | ty::Placeholder(..)
2498            ) {
2499                let mut err = self.tcx().dcx().struct_span_err(
2500                    span,
2501                    "the lhs of a forall where clause must be \
2502                         an alias, placeholder, or lifetime",
2503                );
2504                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the bad clause is {0}", clause))
    })format!("the bad clause is {clause}"));
2505                err.emit();
2506            }
2507        }
2508        let ty = type_outlives.iter().map(|c| c.map_bound(ty::ClauseKind::TypeOutlives));
2509        let reg =
2510            region_outlives.iter().map(|&c| ty::Binder::dummy(ty::ClauseKind::RegionOutlives(c)));
2511        let explicit_clauses: Vec<ty::Clause<'tcx>> =
2512            ty.chain(reg).map(|c| c.upcast(self.tcx())).collect();
2513        for elaborated in ty::elaborate::elaborate(self.tcx(), explicit_clauses.iter().copied()) {
2514            if !explicit_clauses.contains(&elaborated) {
2515                let mut err = self.tcx().dcx().struct_span_err(
2516                    span,
2517                    "all implied bounds of clauses must themselves be \
2518                     included in the where clause of a forall",
2519                );
2520                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing clause is {0}",
                elaborated))
    })format!("missing clause is {elaborated}"));
2521                err.emit();
2522            }
2523        }
2524
2525        let mut builder = TransitiveRelationBuilder::default();
2526        for &ty::OutlivesClause(r1, r2) in &region_outlives {
2527            builder.add(r1, r2);
2528        }
2529        // Deliberately unelaborated: the assumptions of a `forall` are exactly the ones
2530        // written down in the test, no extra ones hidden behind the scenes.
2531        ty::region_constraint::Assumptions::new_unelaborated(type_outlives, builder.freeze())
2532    }
2533
2534    {}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2534u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fallback_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fallback_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("actual")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("actual");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fallback_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            fn err<'tcx>(tcx: TyCtxt<'tcx>, expected_span: Span,
                expected: impl std::fmt::Debug, actual_span: Option<Span>,
                actual: impl std::fmt::Debug) {
                let mut err =
                    tcx.dcx().struct_span_err(expected_span,
                        "forall expect clause failed");
                if let Some(actual_span) = actual_span {
                    err.span_note(actual_span, "constraint from here");
                }
                err.note(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected: {0:#?}",
                                    expected))
                        }));
                err.note(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
                        }));
                err.emit();
            }
            let span_of_and =
                |c: &And<_, _>|
                    {
                        c.0.iter().map(|leaf|
                                    leaf.span()).reduce(|span: Span, acc| acc.to(span))
                    };
            let span_of_or =
                |c: &Or<_, _>|
                    {
                        c.0.iter().flat_map(|and|
                                    span_of_and(and)).reduce(|span, acc| acc.to(span))
                    };
            let check_leaf_constraint =
                |expected: LeafRegionConstraint<_, _>,
                    actual: LeafRegionConstraint<_, _>|
                    {
                        if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected,
                                    expected_span) = expected &&
                                let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual,
                                    actual_span) = actual {
                            let expected_anon =
                                self.tcx().anonymize_bound_vars(expected);
                            let actual_anon = self.tcx().anonymize_bound_vars(actual);
                            if expected_anon != actual_anon {
                                let mut err =
                                    self.tcx().dcx().struct_span_err(expected_span,
                                        "forall expect clause failed");
                                err.span_note(actual_span, "constraint from here");
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("expected: {0:#?}",
                                                    expected))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("expected_anon: {0:#?}",
                                                    expected_anon))
                                        }));
                                err.note(::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("actual_anon: {0:#?}",
                                                    actual_anon))
                                        }));
                                err.emit();
                            }
                        } else if expected.clone().without_span() !=
                                actual.clone().without_span() {
                            err(self.tcx(), expected.span(), expected,
                                Some(actual.span()), actual);
                        }
                    };
            let check_and_constraint =
                |expected: And<_, _>, actual: And<_, _>|
                    {
                        if expected.0.len() != actual.0.len() {
                            err(self.tcx(),
                                span_of_and(&expected).unwrap_or(fallback_span), expected,
                                span_of_and(&actual), actual)
                        } else {
                            for (expected, actual) in
                                expected.0.into_iter().zip(actual.0.into_iter()) {
                                check_leaf_constraint(expected, actual);
                            }
                        }
                    };
            let check_or_constraint =
                |expected: Or<_, _>, actual: Or<_, _>|
                    {
                        if expected.0.len() != actual.0.len() {
                            err(self.tcx(),
                                span_of_or(&expected).unwrap_or(fallback_span), expected,
                                span_of_or(&actual), actual)
                        } else {
                            for (expected, actual) in
                                expected.0.into_iter().zip(actual.0.into_iter()) {
                                check_and_constraint(expected, actual);
                            }
                        }
                    };
            check_or_constraint(expected.or_constraint.clone(),
                actual.or_constraint.clone());
            check_and_constraint(expected.and_constraint.clone(),
                actual.and_constraint.clone());
        }
    }
}#[instrument(level = "debug", skip(self))]
2535    fn check_test_binder_region_constraints(
2536        &self,
2537        fallback_span: Span,
2538        expected: &SolverRegionConstraint<'tcx>,
2539        actual: &SolverRegionConstraint<'tcx>,
2540    ) {
2541        fn err<'tcx>(
2542            tcx: TyCtxt<'tcx>,
2543            expected_span: Span,
2544            expected: impl std::fmt::Debug,
2545            actual_span: Option<Span>,
2546            actual: impl std::fmt::Debug,
2547        ) {
2548            let mut err = tcx.dcx().struct_span_err(expected_span, "forall expect clause failed");
2549            if let Some(actual_span) = actual_span {
2550                err.span_note(actual_span, "constraint from here");
2551            }
2552            err.note(format!("expected: {expected:#?}"));
2553            err.note(format!("actual: {actual:#?}"));
2554            err.emit();
2555        }
2556
2557        let span_of_and = |c: &And<_, _>| {
2558            c.0.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span))
2559        };
2560
2561        let span_of_or = |c: &Or<_, _>| {
2562            c.0.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span))
2563        };
2564
2565        let check_leaf_constraint =
2566            |expected: LeafRegionConstraint<_, _>, actual: LeafRegionConstraint<_, _>| {
2567                if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected, expected_span) =
2568                    expected
2569                    && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual, actual_span) = actual
2570                {
2571                    let expected_anon = self.tcx().anonymize_bound_vars(expected);
2572                    let actual_anon = self.tcx().anonymize_bound_vars(actual);
2573                    if expected_anon != actual_anon {
2574                        let mut err = self
2575                            .tcx()
2576                            .dcx()
2577                            .struct_span_err(expected_span, "forall expect clause failed");
2578                        err.span_note(actual_span, "constraint from here");
2579                        err.note(format!("expected: {expected:#?}"));
2580                        err.note(format!("actual: {actual:#?}"));
2581                        err.note(format!("expected_anon: {expected_anon:#?}"));
2582                        err.note(format!("actual_anon: {actual_anon:#?}"));
2583                        err.emit();
2584                    }
2585                } else if expected.clone().without_span() != actual.clone().without_span() {
2586                    err(self.tcx(), expected.span(), expected, Some(actual.span()), actual);
2587                }
2588            };
2589
2590        let check_and_constraint = |expected: And<_, _>, actual: And<_, _>| {
2591            if expected.0.len() != actual.0.len() {
2592                err(
2593                    self.tcx(),
2594                    span_of_and(&expected).unwrap_or(fallback_span),
2595                    expected,
2596                    span_of_and(&actual),
2597                    actual,
2598                )
2599            } else {
2600                for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2601                    check_leaf_constraint(expected, actual);
2602                }
2603            }
2604        };
2605
2606        let check_or_constraint = |expected: Or<_, _>, actual: Or<_, _>| {
2607            if expected.0.len() != actual.0.len() {
2608                err(
2609                    self.tcx(),
2610                    span_of_or(&expected).unwrap_or(fallback_span),
2611                    expected,
2612                    span_of_or(&actual),
2613                    actual,
2614                )
2615            } else {
2616                for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2617                    check_and_constraint(expected, actual);
2618                }
2619            }
2620        };
2621
2622        check_or_constraint(expected.or_constraint.clone(), actual.or_constraint.clone());
2623        check_and_constraint(expected.and_constraint.clone(), actual.and_constraint.clone());
2624    }
2625
2626    {}
#[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/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2626u32),
                                    ::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))]
2627    fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {
2628        let body = self.infcx.instantiate_binder_with_fresh_vars(
2629            exists.span,
2630            BoundRegionConversionTime::HigherRankedType,
2631            exists.binder,
2632        );
2633        self.check_test_binder_body(body);
2634    }
2635}
2636
2637pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2638    let items = tcx.hir_crate_items(());
2639    let res =
2640        items
2641            .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2642            .and(
2643                items.par_impl_items(|item| {
2644                    tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2645                }),
2646            )
2647            .and(items.par_trait_items(|item| {
2648                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2649            }))
2650            .and(items.par_foreign_items(|item| {
2651                tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2652            }))
2653            .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2654            .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2655
2656    super::entry::check_for_entry_fn(tcx)?;
2657
2658    res
2659}
2660
2661fn lint_redundant_lifetimes<'tcx>(
2662    tcx: TyCtxt<'tcx>,
2663    owner_id: LocalDefId,
2664    outlives_env: &OutlivesEnvironment<'tcx>,
2665) {
2666    let def_kind = tcx.def_kind(owner_id);
2667    match def_kind {
2668        DefKind::Struct
2669        | DefKind::Union
2670        | DefKind::Enum
2671        | DefKind::Trait
2672        | DefKind::TraitAlias
2673        | DefKind::Fn
2674        | DefKind::Const
2675        | DefKind::Impl { of_trait: _ }
2676        | DefKind::TestBinderConstraints => {
2677            // Proceed
2678        }
2679        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2680            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2681                // Don't check for redundant lifetimes for associated items of trait
2682                // implementations, since the signature is required to be compatible
2683                // with the trait, even if the implementation implies some lifetimes
2684                // are redundant.
2685                return;
2686            }
2687        }
2688        DefKind::Mod
2689        | DefKind::Variant
2690        | DefKind::TyAlias
2691        | DefKind::ForeignTy
2692        | DefKind::TyParam
2693        | DefKind::ConstParam
2694        | DefKind::Static { .. }
2695        | DefKind::Ctor(_, _)
2696        | DefKind::Macro(_)
2697        | DefKind::ExternCrate
2698        | DefKind::Use
2699        | DefKind::ForeignMod
2700        | DefKind::AnonConst
2701        | DefKind::OpaqueTy
2702        | DefKind::Field
2703        | DefKind::LifetimeParam
2704        | DefKind::GlobalAsm
2705        | DefKind::Closure
2706        | DefKind::SyntheticCoroutineBody => return,
2707    }
2708
2709    // The ordering of this lifetime map is a bit subtle.
2710    //
2711    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2712    // where we can prove that `'candidate = 'victim`.
2713    //
2714    // `'static` must come first in this list because we can never replace `'static` with
2715    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2716    // suggest replacing `'a` with `'static`.
2717    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];
2718    lifetimes.extend(
2719        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2720    );
2721    // If we are in a function, add its late-bound lifetimes too.
2722    if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2723        for (idx, var) in tcx
2724            .fn_sig(owner_id)
2725            .instantiate_identity()
2726            .skip_norm_wip()
2727            .bound_vars()
2728            .iter()
2729            .enumerate()
2730        {
2731            let ty::BoundVariableKind::Region(kind) = var else { continue };
2732            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2733            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2734        }
2735    }
2736    lifetimes.retain(|candidate| candidate.is_named(tcx));
2737
2738    // Keep track of lifetimes which have already been replaced with other lifetimes.
2739    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2740    // both `'a` and `'b`.
2741    let mut shadowed = FxHashSet::default();
2742
2743    for (idx, &candidate) in lifetimes.iter().enumerate() {
2744        // Don't suggest removing a lifetime twice. We only need to check this
2745        // here and not up in the `victim` loop because equality is transitive,
2746        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2747        // A's victim loop.
2748        if shadowed.contains(&candidate) {
2749            continue;
2750        }
2751
2752        for &victim in &lifetimes[(idx + 1)..] {
2753            // All region parameters should have a `DefId` available as:
2754            // - Late-bound parameters should be of the`BrNamed` variety,
2755            // since we get these signatures straight from `hir_lowering`.
2756            // - Early-bound parameters unconditionally have a `DefId` available.
2757            //
2758            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2759            // can't really suggest to remove them.
2760            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2761                continue;
2762            };
2763
2764            // Do not rename lifetimes not local to this item since they'll overlap
2765            // with the lint running on the parent. We still want to consider parent
2766            // lifetimes which make child lifetimes redundant, otherwise we would
2767            // have truncated the `identity_for_item` args above.
2768            if tcx.parent(def_id) != owner_id.to_def_id() {
2769                continue;
2770            }
2771
2772            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2773            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2774                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2775            {
2776                shadowed.insert(victim);
2777                tcx.emit_node_span_lint(
2778                    REDUNDANT_LIFETIMES,
2779                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2780                    tcx.def_span(def_id),
2781                    RedundantLifetimeArgsLint { candidate, victim },
2782                );
2783            }
2784        }
2785    }
2786}
2787
2788#[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)]
2789#[diag("unnecessary lifetime parameter `{$victim}`")]
2790#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2791struct RedundantLifetimeArgsLint<'tcx> {
2792    /// The lifetime we have found to be redundant.
2793    victim: ty::Region<'tcx>,
2794    // The lifetime we can replace the victim with.
2795    candidate: ty::Region<'tcx>,
2796}
2797
2798#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderBody<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderBody {
            foralls: ::core::clone::Clone::clone(&self.foralls),
            exists: ::core::clone::Clone::clone(&self.exists),
            constraints: ::core::clone::Clone::clone(&self.constraints),
            predicates: ::core::clone::Clone::clone(&self.predicates),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderBody<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "TestBinderBody", "foralls", &self.foralls, "exists",
            &self.exists, "constraints", &self.constraints, "predicates",
            &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderBody<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderBody {
                            foralls: __binding_0,
                            exists: __binding_1,
                            constraints: __binding_2,
                            predicates: __binding_3 } => {
                            TestBinderBody {
                                foralls: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                exists: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                constraints: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                                predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderBody {
                        foralls: __binding_0,
                        exists: __binding_1,
                        constraints: __binding_2,
                        predicates: __binding_3 } => {
                        TestBinderBody {
                            foralls: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            exists: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            constraints: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                            predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderBody<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderBody {
                        foralls: ref __binding_0,
                        exists: ref __binding_1,
                        constraints: ref __binding_2,
                        predicates: ref __binding_3 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2799pub(crate) struct TestBinderBody<'tcx> {
2800    pub foralls: Vec<TestBinderForall<'tcx>>,
2801    pub exists: Vec<TestBinderExists<'tcx>>,
2802    /// Constraints to be inserted directly into constraint storage to be proven
2803    pub constraints: SolverRegionConstraint<'tcx>,
2804    /// Constraints declared using `where` syntax, used via `register_obligation`
2805    pub predicates: Vec<(ty::Binder<'tcx, ty::ClauseKind<'tcx>>, Span)>,
2806}
2807
2808#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderForall<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderForall {
            span: ::core::clone::Clone::clone(&self.span),
            binder: ::core::clone::Clone::clone(&self.binder),
            assert_on_exit: ::core::clone::Clone::clone(&self.assert_on_exit),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderForall<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "TestBinderForall", "span", &self.span, "binder", &self.binder,
            "assert_on_exit", &&self.assert_on_exit)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderForall<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderForall {
                            span: __binding_0,
                            binder: __binding_1,
                            assert_on_exit: __binding_2 } => {
                            TestBinderForall {
                                span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                assert_on_exit: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderForall {
                        span: __binding_0,
                        binder: __binding_1,
                        assert_on_exit: __binding_2 } => {
                        TestBinderForall {
                            span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            assert_on_exit: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderForall<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderForall {
                        span: ref __binding_0,
                        binder: ref __binding_1,
                        assert_on_exit: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2809pub(crate) struct TestBinderForall<'tcx> {
2810    pub span: Span,
2811    pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,
2812    pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>,
2813}
2814
2815#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderExists<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        TestBinderExists {
            span: ::core::clone::Clone::clone(&self.span),
            binder: ::core::clone::Clone::clone(&self.binder),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderExists<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TestBinderExists", "span", &self.span, "binder", &&self.binder)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderExists<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TestBinderExists { span: __binding_0, binder: __binding_1 }
                            => {
                            TestBinderExists {
                                span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TestBinderExists { span: __binding_0, binder: __binding_1 }
                        => {
                        TestBinderExists {
                            span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TestBinderExists<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TestBinderExists {
                        span: ref __binding_0, binder: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2816pub(crate) struct TestBinderExists<'tcx> {
2817    pub span: Span,
2818    pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,
2819}
2820
2821#[derive(#[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
    WithWhereClauses<'tcx, T> {
    #[inline]
    fn clone(&self) -> Self {
        WithWhereClauses {
            value: ::core::clone::Clone::clone(&self.value),
            type_outlives: ::core::clone::Clone::clone(&self.type_outlives),
            region_outlives: ::core::clone::Clone::clone(&self.region_outlives),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for
    WithWhereClauses<'tcx, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "WithWhereClauses", "value", &self.value, "type_outlives",
            &self.type_outlives, "region_outlives", &&self.region_outlives)
    }
}Debug, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for WithWhereClauses<'tcx, T> where
            T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        WithWhereClauses {
                            value: __binding_0,
                            type_outlives: __binding_1,
                            region_outlives: __binding_2 } => {
                            WithWhereClauses {
                                value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                type_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                region_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    WithWhereClauses {
                        value: __binding_0,
                        type_outlives: __binding_1,
                        region_outlives: __binding_2 } => {
                        WithWhereClauses {
                            value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            type_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            region_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for WithWhereClauses<'tcx, T> where
            T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    WithWhereClauses {
                        value: ref __binding_0,
                        type_outlives: ref __binding_1,
                        region_outlives: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
2822pub(crate) struct WithWhereClauses<'tcx, T> {
2823    pub value: T,
2824
2825    // The where clauses on the forall. These eventually will probably get stored inside
2826    // `ty::Binder` but they're here for now.
2827    pub type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,
2828    pub region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,
2829}