Skip to main content

rustc_trait_selection/traits/
mod.rs

1//! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5pub mod auto_trait;
6pub(crate) mod coherence;
7pub mod const_evaluatable;
8mod dyn_compatibility;
9pub mod effects;
10mod engine;
11mod fulfill;
12pub mod misc;
13pub mod normalize;
14pub mod outlives_bounds;
15pub mod project;
16pub mod query;
17#[allow(hidden_glob_reexports)]
18mod select;
19pub mod specialize;
20mod structural_normalize;
21#[allow(hidden_glob_reexports)]
22mod util;
23pub mod vtable;
24pub mod wf;
25
26use std::fmt::Debug;
27use std::ops::ControlFlow;
28
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31pub use rustc_infer::traits::*;
32use rustc_macros::TypeVisitable;
33use rustc_middle::query::Providers;
34use rustc_middle::span_bug;
35use rustc_middle::ty::error::{ExpectedFound, TypeError};
36use rustc_middle::ty::{
37    self, Clause, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder,
38    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode,
39    Unnormalized, Upcast,
40};
41use rustc_span::Span;
42use rustc_span::def_id::DefId;
43use tracing::{debug, instrument};
44
45pub use self::coherence::{
46    InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams,
47    add_placeholder_note, orphan_check_trait_ref, overlapping_inherent_impls,
48    overlapping_trait_impls,
49};
50pub use self::dyn_compatibility::{
51    DynCompatibilityViolation, dyn_compatibility_violations_for_assoc_item,
52    hir_ty_lowering_dyn_compatibility_violations, is_vtable_safe_method,
53};
54pub use self::engine::{ObligationCtxt, TraitEngineExt};
55pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation};
56pub use self::normalize::NormalizeExt;
57pub use self::project::{normalize_inherent_projection, normalize_projection_term};
58pub use self::select::{
59    EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache,
60    SelectionContext,
61};
62pub use self::specialize::specialization_graph::{
63    FutureCompatOverlapError, FutureCompatOverlapErrorKind,
64};
65pub use self::specialize::{
66    OverlapError, specialization_graph, translate_args, translate_args_with_cause,
67};
68pub use self::structural_normalize::StructurallyNormalizeExt;
69pub use self::util::{
70    BoundVarReplacer, PlaceholderReplacer, elaborate, expand_trait_aliases, impl_item_is_final,
71    sizedness_fast_path, supertrait_def_ids, supertraits, transitive_bounds_that_define_assoc_item,
72    upcast_choices, with_replaced_escaping_bound_vars,
73};
74use crate::error_reporting::InferCtxtErrorExt;
75use crate::infer::outlives::env::OutlivesEnvironment;
76use crate::infer::{InferCtxt, TyCtxtInferExt};
77use crate::regions::InferCtxtRegionExt;
78use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
79
80#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FulfillmentError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "FulfillmentError", "obligation", &self.obligation, "code",
            &self.code, "root_obligation", &&self.root_obligation)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for FulfillmentError<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    FulfillmentError {
                        obligation: ref __binding_0,
                        code: ref __binding_1,
                        root_obligation: 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)]
81pub struct FulfillmentError<'tcx> {
82    pub obligation: PredicateObligation<'tcx>,
83    pub code: FulfillmentErrorCode<'tcx>,
84    /// Diagnostics only: the 'root' obligation which resulted in
85    /// the failure to process `obligation`. This is the obligation
86    /// that was initially passed to `register_predicate_obligation`
87    pub root_obligation: PredicateObligation<'tcx>,
88}
89
90impl<'tcx> FulfillmentError<'tcx> {
91    pub fn new(
92        obligation: PredicateObligation<'tcx>,
93        code: FulfillmentErrorCode<'tcx>,
94        root_obligation: PredicateObligation<'tcx>,
95    ) -> FulfillmentError<'tcx> {
96        FulfillmentError { obligation, code, root_obligation }
97    }
98
99    pub fn is_true_error(&self) -> bool {
100        match self.code {
101            FulfillmentErrorCode::Select(_)
102            | FulfillmentErrorCode::Project(_)
103            | FulfillmentErrorCode::Subtype(_, _)
104            | FulfillmentErrorCode::ConstEquate(_, _) => true,
105            FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
106                false
107            }
108        }
109    }
110}
111
112#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FulfillmentErrorCode<'tcx> {
    #[inline]
    fn clone(&self) -> FulfillmentErrorCode<'tcx> {
        match self {
            FulfillmentErrorCode::Cycle(__self_0) =>
                FulfillmentErrorCode::Cycle(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Select(__self_0) =>
                FulfillmentErrorCode::Select(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Project(__self_0) =>
                FulfillmentErrorCode::Project(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Subtype(__self_0, __self_1) =>
                FulfillmentErrorCode::Subtype(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            FulfillmentErrorCode::ConstEquate(__self_0, __self_1) =>
                FulfillmentErrorCode::ConstEquate(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            FulfillmentErrorCode::Ambiguity { overflow: __self_0 } =>
                FulfillmentErrorCode::Ambiguity {
                    overflow: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for FulfillmentErrorCode<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    FulfillmentErrorCode::Cycle(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Select(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Project(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Subtype(ref __binding_0,
                        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);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::ConstEquate(ref __binding_0,
                        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);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Ambiguity { overflow: ref __binding_0
                        } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
113pub enum FulfillmentErrorCode<'tcx> {
114    /// Inherently impossible to fulfill; this trait is implemented if and only
115    /// if it is already implemented.
116    Cycle(PredicateObligations<'tcx>),
117    Select(SelectionError<'tcx>),
118    Project(MismatchedProjectionTypes<'tcx>),
119    Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
120    ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
121    Ambiguity {
122        /// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
123        /// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
124        /// emitting a fatal error instead.
125        overflow: Option<bool>,
126    },
127}
128
129impl<'tcx> Debug for FulfillmentErrorCode<'tcx> {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match *self {
132            FulfillmentErrorCode::Select(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
133            FulfillmentErrorCode::Project(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
134            FulfillmentErrorCode::Subtype(ref a, ref b) => {
135                f.write_fmt(format_args!("CodeSubtypeError({0:?}, {1:?})", a, b))write!(f, "CodeSubtypeError({a:?}, {b:?})")
136            }
137            FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
138                f.write_fmt(format_args!("CodeConstEquateError({0:?}, {1:?})", a, b))write!(f, "CodeConstEquateError({a:?}, {b:?})")
139            }
140            FulfillmentErrorCode::Ambiguity { overflow: None } => f.write_fmt(format_args!("Ambiguity"))write!(f, "Ambiguity"),
141            FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
142                f.write_fmt(format_args!("Overflow({0})", suggest_increasing_limit))write!(f, "Overflow({suggest_increasing_limit})")
143            }
144            FulfillmentErrorCode::Cycle(ref cycle) => f.write_fmt(format_args!("Cycle({0:?})", cycle))write!(f, "Cycle({cycle:?})"),
145        }
146    }
147}
148
149/// Whether to skip the leak check, as part of a future compatibility warning step.
150///
151/// The "default" for skip-leak-check corresponds to the current
152/// behavior (do not skip the leak check) -- not the behavior we are
153/// transitioning into.
154#[derive(#[automatically_derived]
impl ::core::marker::Copy for SkipLeakCheck { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SkipLeakCheck {
    #[inline]
    fn clone(&self) -> SkipLeakCheck { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SkipLeakCheck {
    #[inline]
    fn eq(&self, other: &SkipLeakCheck) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SkipLeakCheck {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SkipLeakCheck {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                SkipLeakCheck::Yes => "Yes",
                SkipLeakCheck::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for SkipLeakCheck {
    #[inline]
    fn default() -> SkipLeakCheck { Self::No }
}Default)]
155pub enum SkipLeakCheck {
156    Yes,
157    #[default]
158    No,
159}
160
161impl SkipLeakCheck {
162    fn is_yes(self) -> bool {
163        self == SkipLeakCheck::Yes
164    }
165}
166
167/// The mode that trait queries run in.
168#[derive(#[automatically_derived]
impl ::core::marker::Copy for TraitQueryMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TraitQueryMode {
    #[inline]
    fn clone(&self) -> TraitQueryMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitQueryMode {
    #[inline]
    fn eq(&self, other: &TraitQueryMode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TraitQueryMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for TraitQueryMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TraitQueryMode::Standard => "Standard",
                TraitQueryMode::Canonical => "Canonical",
            })
    }
}Debug)]
169pub enum TraitQueryMode {
170    /// Standard/un-canonicalized queries get accurate
171    /// spans etc. passed in and hence can do reasonable
172    /// error reporting on their own.
173    Standard,
174    /// Canonical queries get dummy spans and hence
175    /// must generally propagate errors to
176    /// pre-canonicalization callsites.
177    Canonical,
178}
179
180/// Creates predicate obligations from the generic bounds.
181#[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("predicates_for_generics",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(181u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["generic_bounds"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_bounds)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: _ = loop {};
            return __tracing_attr_fake_return;
        }
        {
            generic_bounds.into_iter().enumerate().map(move
                    |(idx, (clause, span))|
                    Obligation {
                        cause: cause(idx, span),
                        recursion_depth: 0,
                        param_env,
                        predicate: normalize_predicate(clause).as_predicate(),
                    })
        }
    }
}#[instrument(level = "debug", skip(cause, param_env, normalize_predicate))]
182pub fn predicates_for_generics<'tcx>(
183    cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
184    mut normalize_predicate: impl FnMut(Unnormalized<'tcx, Clause<'tcx>>) -> Clause<'tcx>,
185    param_env: ty::ParamEnv<'tcx>,
186    generic_bounds: ty::InstantiatedPredicates<'tcx>,
187) -> impl Iterator<Item = PredicateObligation<'tcx>> {
188    generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
189        cause: cause(idx, span),
190        recursion_depth: 0,
191        param_env,
192        predicate: normalize_predicate(clause).as_predicate(),
193    })
194}
195
196/// Determines whether the type `ty` is known to meet `bound` and
197/// returns true if so. Returns false if `ty` either does not meet
198/// `bound` or is not known to meet bound (note that this is
199/// conservative towards *no impl*, which is the opposite of the
200/// `evaluate` methods).
201pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
202    infcx: &InferCtxt<'tcx>,
203    param_env: ty::ParamEnv<'tcx>,
204    ty: Ty<'tcx>,
205    def_id: DefId,
206) -> bool {
207    let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
208    pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
209}
210
211/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
212///
213/// Ping me on zulip if you want to use this method and need help with finding
214/// an appropriate replacement.
215x;#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
216fn pred_known_to_hold_modulo_regions<'tcx>(
217    infcx: &InferCtxt<'tcx>,
218    param_env: ty::ParamEnv<'tcx>,
219    pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
220) -> bool {
221    let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
222
223    let result = infcx.evaluate_obligation_no_overflow(&obligation);
224    debug!(?result);
225
226    if result.must_apply_modulo_regions() {
227        true
228    } else if result.may_apply() && !infcx.next_trait_solver() {
229        // Sometimes obligations are ambiguous because the recursive evaluator
230        // is not smart enough, so we fall back to fulfillment when we're not certain
231        // that an obligation holds or not. Even still, we must make sure that
232        // the we do no inference in the process of checking this obligation.
233        let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
234        infcx.probe(|_| {
235            let ocx = ObligationCtxt::new(infcx);
236            ocx.register_obligation(obligation);
237
238            let errors = ocx.evaluate_obligations_error_on_ambiguity();
239            match errors.as_slice() {
240                // Only known to hold if we did no inference.
241                [] => infcx.resolve_vars_if_possible(goal) == goal,
242
243                errors => {
244                    debug!(?errors);
245                    false
246                }
247            }
248        })
249    } else {
250        false
251    }
252}
253
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("do_normalize_predicates",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(254u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["cause",
                                                    "predicates"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicates)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if tcx.next_trait_solver_globally() { return Ok(predicates); }
            let span = cause.span;
            let infcx =
                tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let predicates =
                ocx.normalize(&cause, elaborated_env,
                    Unnormalized::new_wip(predicates));
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:291",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(291u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("do_normalize_predicates: normalized predicates = {0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let errors =
                infcx.resolve_regions(cause.body_id, elaborated_env, []);
            if !errors.is_empty() {
                tcx.dcx().span_delayed_bug(span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("failed region resolution while normalizing {0:?}: {1:?}",
                                    elaborated_env, errors))
                        }));
            }
            match infcx.fully_resolve(predicates) {
                Ok(predicates) => Ok(predicates),
                Err(fixup_err) => {
                    Err(tcx.dcx().span_delayed_bug(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("inference variables in normalized parameter environment: {0}",
                                            fixup_err))
                                })))
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, elaborated_env))]
255fn do_normalize_predicates<'tcx>(
256    tcx: TyCtxt<'tcx>,
257    cause: ObligationCause<'tcx>,
258    elaborated_env: ty::ParamEnv<'tcx>,
259    predicates: Vec<ty::Clause<'tcx>>,
260) -> Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> {
261    // Even if we move back to eager normalization elsewhere,
262    // param env normalization remains lazy in the next solver.
263    if tcx.next_trait_solver_globally() {
264        return Ok(predicates);
265    }
266
267    // FIXME. We should really... do something with these region
268    // obligations. But this call just continues the older
269    // behavior (i.e., doesn't cause any new bugs), and it would
270    // take some further refactoring to actually solve them. In
271    // particular, we would have to handle implied bounds
272    // properly, and that code is currently largely confined to
273    // regionck (though I made some efforts to extract it
274    // out). -nmatsakis
275    //
276    // @arielby: In any case, these obligations are checked
277    // by wfcheck anyway, so I'm not sure we have to check
278    // them here too, and we will remove this function when
279    // we move over to lazy normalization *anyway*.
280    let span = cause.span;
281    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
282    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
283    let predicates = ocx.normalize(&cause, elaborated_env, Unnormalized::new_wip(predicates));
284
285    let errors = ocx.evaluate_obligations_error_on_ambiguity();
286    if !errors.is_empty() {
287        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
288        return Err(reported);
289    }
290
291    debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
292
293    // We can use the `elaborated_env` here; the region code only
294    // cares about declarations like `'a: 'b`.
295    // FIXME: It's very weird that we ignore region obligations but apparently
296    // still need to use `resolve_regions` as we need the resolved regions in
297    // the normalized predicates.
298    let errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
299    if !errors.is_empty() {
300        tcx.dcx().span_delayed_bug(
301            span,
302            format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
303        );
304    }
305
306    match infcx.fully_resolve(predicates) {
307        Ok(predicates) => Ok(predicates),
308        Err(fixup_err) => {
309            // If we encounter a fixup error, it means that some type
310            // variable wound up unconstrained. That can happen for
311            // ill-formed impls, so we delay a bug here instead of
312            // immediately ICEing and let type checking report the
313            // actual user-facing errors.
314            Err(tcx.dcx().span_delayed_bug(
315                span,
316                format!("inference variables in normalized parameter environment: {fixup_err}"),
317            ))
318        }
319    }
320}
321
322// FIXME: this is gonna need to be removed ...
323/// Normalizes the parameter environment, reporting errors if they occur.
324#[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("normalize_param_env_or_error",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(324u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["unnormalized_env",
                                                    "cause"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::ParamEnv<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut predicates: Vec<_> =
                util::elaborate(tcx,
                        unnormalized_env.caller_bounds().into_iter().map(|predicate|
                                {
                                    if tcx.features().generic_const_exprs() ||
                                            tcx.next_trait_solver_globally() {
                                        return predicate;
                                    }
                                    struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
                                    impl<'tcx> TypeFolder<TyCtxt<'tcx>> for
                                        ConstNormalizer<'tcx> {
                                        fn cx(&self) -> TyCtxt<'tcx> { self.0 }
                                        fn fold_const(&mut self, c: ty::Const<'tcx>)
                                            -> ty::Const<'tcx> {
                                            if c.has_escaping_bound_vars() {
                                                return ty::Const::new_misc_error(self.0);
                                            }
                                            if let ty::ConstKind::Unevaluated(uv) = c.kind() &&
                                                    self.0.def_kind(uv.def) == DefKind::AnonConst {
                                                let infcx =
                                                    self.0.infer_ctxt().build(TypingMode::non_body_analysis());
                                                let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
                                                if !(!c.has_infer() && !c.has_placeholders()) {
                                                    ::core::panicking::panic("assertion failed: !c.has_infer() && !c.has_placeholders()")
                                                };
                                                return c;
                                            }
                                            c
                                        }
                                    }
                                    predicate.fold_with(&mut ConstNormalizer(tcx))
                                })).collect();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:417",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(417u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-predicates={0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let elaborated_env =
                ty::ParamEnv::new(tcx.mk_clauses(&predicates));
            if !elaborated_env.has_aliases() { return elaborated_env; }
            let outlives_predicates: Vec<_> =
                predicates.extract_if(..,
                        |predicate|
                            {

                                #[allow(non_exhaustive_omitted_patterns)]
                                match predicate.kind().skip_binder() {
                                    ty::ClauseKind::TypeOutlives(..) => true,
                                    _ => false,
                                }
                            }).collect();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:448",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(448u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: predicates=(non-outlives={0:?}, outlives={1:?})",
                                                                predicates, outlives_predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let Ok(non_outlives_predicates) =
                do_normalize_predicates(tcx, cause.clone(), elaborated_env,
                    predicates) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:456",
                                            "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(456u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving non-outlives predicates")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return elaborated_env;
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:460",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(460u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: non-outlives predicates={0:?}",
                                                                non_outlives_predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let outlives_env =
                non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
            let outlives_env =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
            let Ok(outlives_predicates) =
                do_normalize_predicates(tcx, cause, outlives_env,
                    outlives_predicates) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:471",
                                            "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(471u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving outlives predicates")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return elaborated_env;
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:474",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(474u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: outlives predicates={0:?}",
                                                                outlives_predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let mut predicates = non_outlives_predicates;
            predicates.extend(outlives_predicates);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:478",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(478u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final predicates={0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            ty::ParamEnv::new(tcx.mk_clauses(&predicates))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
325pub fn normalize_param_env_or_error<'tcx>(
326    tcx: TyCtxt<'tcx>,
327    unnormalized_env: ty::ParamEnv<'tcx>,
328    cause: ObligationCause<'tcx>,
329) -> ty::ParamEnv<'tcx> {
330    // I'm not wild about reporting errors here; I'd prefer to
331    // have the errors get reported at a defined place (e.g.,
332    // during typeck). Instead I have all parameter
333    // environments, in effect, going through this function
334    // and hence potentially reporting errors. This ensures of
335    // course that we never forget to normalize (the
336    // alternative seemed like it would involve a lot of
337    // manual invocations of this fn -- and then we'd have to
338    // deal with the errors at each of those sites).
339    //
340    // In any case, in practice, typeck constructs all the
341    // parameter environments once for every fn as it goes,
342    // and errors will get reported then; so outside of type inference we
343    // can be sure that no errors should occur.
344    let mut predicates: Vec<_> = util::elaborate(
345        tcx,
346        unnormalized_env.caller_bounds().into_iter().map(|predicate| {
347            if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
348                return predicate;
349            }
350
351            struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
352
353            impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
354                fn cx(&self) -> TyCtxt<'tcx> {
355                    self.0
356                }
357
358                fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
359                    // FIXME(return_type_notation): track binders in this normalizer, as
360                    // `ty::Const::normalize` can only work with properly preserved binders.
361
362                    if c.has_escaping_bound_vars() {
363                        return ty::Const::new_misc_error(self.0);
364                    }
365
366                    // While it is pretty sus to be evaluating things with an empty param env, it
367                    // should actually be okay since without `feature(generic_const_exprs)` the only
368                    // const arguments that have a non-empty param env are array repeat counts. These
369                    // do not appear in the type system though.
370                    if let ty::ConstKind::Unevaluated(uv) = c.kind()
371                        && self.0.def_kind(uv.def) == DefKind::AnonConst
372                    {
373                        let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
374                        let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
375                        // We should never wind up with any `infcx` local state when normalizing anon consts
376                        // under min const generics.
377                        assert!(!c.has_infer() && !c.has_placeholders());
378                        return c;
379                    }
380
381                    c
382                }
383            }
384
385            // This whole normalization step is a hack to work around the fact that
386            // `normalize_param_env_or_error` is fundamentally broken from using an
387            // unnormalized param env with a trait solver that expects the param env
388            // to be normalized.
389            //
390            // When normalizing the param env we can end up evaluating obligations
391            // that have been normalized but can only be proven via a where clause
392            // which is still in its unnormalized form. example:
393            //
394            // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
395            // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
396            // we first normalize obligations before proving them so we end up proving
397            // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
398            // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
399            // we cannot prove `T: Trait<u8>`.
400            //
401            // The same thing is true for const generics- attempting to prove
402            // `T: Trait<ConstKind::Unevaluated(...)>` with the same thing as a where clauses
403            // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
404            // the unnormalized where clause `T: Trait<ConstKind::Unevaluated(...)>`. In order
405            // for the obligation to hold `4` must be equal to `ConstKind::Unevaluated(...)`
406            // but as we do not have lazy norm implemented, equating the two consts fails outright.
407            //
408            // Ideally we would not normalize consts here at all but it is required for backwards
409            // compatibility. Eventually when lazy norm is implemented this can just be removed.
410            // We do not normalize types here as there is no backwards compatibility requirement
411            // for us to do so.
412            predicate.fold_with(&mut ConstNormalizer(tcx))
413        }),
414    )
415    .collect();
416
417    debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
418
419    let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
420    if !elaborated_env.has_aliases() {
421        return elaborated_env;
422    }
423
424    // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
425    // normalization expects its param-env to be already normalized, which means we have
426    // a circularity.
427    //
428    // The way we handle this is by normalizing the param-env inside an unnormalized version
429    // of the param-env, which means that if the param-env contains unnormalized projections,
430    // we'll have some normalization failures. This is unfortunate.
431    //
432    // Lazy normalization would basically handle this by treating just the
433    // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
434    //
435    // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
436    // types, so to make the situation less bad, we normalize all the predicates *but*
437    // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
438    // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
439    //
440    // This works fairly well because trait matching does not actually care about param-env
441    // TypeOutlives predicates - these are normally used by regionck.
442    let outlives_predicates: Vec<_> = predicates
443        .extract_if(.., |predicate| {
444            matches!(predicate.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
445        })
446        .collect();
447
448    debug!(
449        "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
450        predicates, outlives_predicates
451    );
452    let Ok(non_outlives_predicates) =
453        do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates)
454    else {
455        // An unnormalized env is better than nothing.
456        debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
457        return elaborated_env;
458    };
459
460    debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
461
462    // Not sure whether it is better to include the unnormalized TypeOutlives predicates
463    // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
464    // predicates here anyway. Keeping them here anyway because it seems safer.
465    let outlives_env = non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
466    let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
467    let Ok(outlives_predicates) =
468        do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates)
469    else {
470        // An unnormalized env is better than nothing.
471        debug!("normalize_param_env_or_error: errored resolving outlives predicates");
472        return elaborated_env;
473    };
474    debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
475
476    let mut predicates = non_outlives_predicates;
477    predicates.extend(outlives_predicates);
478    debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
479    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
480}
481
482/// Deeply normalize the param env using the next solver ignoring
483/// region errors.
484///
485/// FIXME(-Zhigher-ranked-assumptions): this is a hack to work around
486/// the fact that we don't support placeholder assumptions right now
487/// and is necessary for `compare_method_predicate_entailment`, see the
488/// use of this function for more info. We should remove this once we
489/// have proper support for implied bounds on binders.
490#[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("deeply_normalize_param_env_ignoring_regions",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(490u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["unnormalized_env",
                                                    "cause"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::ParamEnv<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let predicates: Vec<_> =
                util::elaborate(tcx,
                        unnormalized_env.caller_bounds().into_iter()).collect();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:499",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(499u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-predicates={0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let elaborated_env =
                ty::ParamEnv::new(tcx.mk_clauses(&predicates));
            if !elaborated_env.has_aliases() { return elaborated_env; }
            let span = cause.span;
            let infcx =
                tcx.infer_ctxt().with_next_trait_solver(true).ignoring_regions().build(TypingMode::non_body_analysis());
            let predicates =
                match crate::solve::deeply_normalize::<_,
                            FulfillmentError<'tcx>>(infcx.at(&cause, elaborated_env),
                        Unnormalized::new_wip(predicates)) {
                    Ok(predicates) => predicates,
                    Err(errors) => {
                        infcx.err_ctxt().report_fulfillment_errors(errors);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:520",
                                                "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(520u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving predicates")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        return elaborated_env;
                    }
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:525",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(525u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("do_normalize_predicates: normalized predicates = {0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            let _errors =
                infcx.resolve_regions(cause.body_id, elaborated_env, []);
            let predicates =
                match infcx.fully_resolve(predicates) {
                    Ok(predicates) => predicates,
                    Err(fixup_err) => {
                        ::rustc_middle::util::bug::span_bug_fmt(span,
                            format_args!("inference variables in normalized parameter environment: {0}",
                                fixup_err))
                    }
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:541",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(541u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final predicates={0:?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            ty::ParamEnv::new(tcx.mk_clauses(&predicates))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
491pub fn deeply_normalize_param_env_ignoring_regions<'tcx>(
492    tcx: TyCtxt<'tcx>,
493    unnormalized_env: ty::ParamEnv<'tcx>,
494    cause: ObligationCause<'tcx>,
495) -> ty::ParamEnv<'tcx> {
496    let predicates: Vec<_> =
497        util::elaborate(tcx, unnormalized_env.caller_bounds().into_iter()).collect();
498
499    debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
500
501    let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
502    if !elaborated_env.has_aliases() {
503        return elaborated_env;
504    }
505
506    let span = cause.span;
507    let infcx = tcx
508        .infer_ctxt()
509        .with_next_trait_solver(true)
510        .ignoring_regions()
511        .build(TypingMode::non_body_analysis());
512    let predicates = match crate::solve::deeply_normalize::<_, FulfillmentError<'tcx>>(
513        infcx.at(&cause, elaborated_env),
514        Unnormalized::new_wip(predicates),
515    ) {
516        Ok(predicates) => predicates,
517        Err(errors) => {
518            infcx.err_ctxt().report_fulfillment_errors(errors);
519            // An unnormalized env is better than nothing.
520            debug!("normalize_param_env_or_error: errored resolving predicates");
521            return elaborated_env;
522        }
523    };
524
525    debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
526    // FIXME(-Zhigher-ranked-assumptions): We're ignoring region errors for now.
527    // There're placeholder constraints `leaking` out.
528    // See the fixme in the enclosing function's docs for more.
529    let _errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
530
531    let predicates = match infcx.fully_resolve(predicates) {
532        Ok(predicates) => predicates,
533        Err(fixup_err) => {
534            span_bug!(
535                span,
536                "inference variables in normalized parameter environment: {}",
537                fixup_err
538            )
539        }
540    };
541    debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
542    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
543}
544
545#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EvaluateConstErr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            EvaluateConstErr::HasGenericsOrInfers =>
                ::core::fmt::Formatter::write_str(f, "HasGenericsOrInfers"),
            EvaluateConstErr::InvalidConstParamTy(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "InvalidConstParamTy", &__self_0),
            EvaluateConstErr::EvaluationFailure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "EvaluationFailure", &__self_0),
        }
    }
}Debug)]
546pub enum EvaluateConstErr {
547    /// The constant being evaluated was either a generic parameter or inference variable, *or*,
548    /// some unevaluated constant with either generic parameters or inference variables in its
549    /// generic arguments.
550    HasGenericsOrInfers,
551    /// The type this constant evaluated to is not valid for use in const generics. This should
552    /// always result in an error when checking the constant is correctly typed for the parameter
553    /// it is an argument to, so a bug is delayed when encountering this.
554    InvalidConstParamTy(ErrorGuaranteed),
555    /// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
556    /// This is also used when the constant was already tainted by error.
557    EvaluationFailure(ErrorGuaranteed),
558}
559
560// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
561// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
562// normalization scheme
563/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
564/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
565/// or inference variables)
566///
567/// You should not call this function unless you are implementing normalization itself. Prefer to use
568/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
569pub fn evaluate_const<'tcx>(
570    infcx: &InferCtxt<'tcx>,
571    ct: ty::Const<'tcx>,
572    param_env: ty::ParamEnv<'tcx>,
573) -> ty::Const<'tcx> {
574    match try_evaluate_const(infcx, ct, param_env) {
575        Ok(ct) => ct,
576        Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
577            ty::Const::new_error(infcx.tcx, e)
578        }
579        Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
580    }
581}
582
583// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
584// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
585// normalization scheme
586/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
587/// or inference variables to succeed in evaluating.
588///
589/// You should not call this function unless you are implementing normalization itself. Prefer to use
590/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
591x;#[instrument(level = "debug", skip(infcx), ret)]
592pub fn try_evaluate_const<'tcx>(
593    infcx: &InferCtxt<'tcx>,
594    ct: ty::Const<'tcx>,
595    param_env: ty::ParamEnv<'tcx>,
596) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
597    let tcx = infcx.tcx;
598    let ct = infcx.resolve_vars_if_possible(ct);
599    debug!(?ct);
600
601    match ct.kind() {
602        ty::ConstKind::Value(..) => Ok(ct),
603        ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
604        ty::ConstKind::Param(_)
605        | ty::ConstKind::Infer(_)
606        | ty::ConstKind::Bound(_, _)
607        | ty::ConstKind::Placeholder(_)
608        | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
609        ty::ConstKind::Unevaluated(uv) => {
610            let opt_anon_const_kind =
611                (tcx.def_kind(uv.def) == DefKind::AnonConst).then(|| tcx.anon_const_kind(uv.def));
612
613            // Postpone evaluation of constants that depend on generic parameters or
614            // inference variables.
615            //
616            // We use `TypingMode::PostAnalysis` here which is not *technically* correct
617            // to be revealing opaque types here as borrowcheck has not run yet. However,
618            // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
619            // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
620            // As a result we always use a revealed env when resolving the instance to evaluate.
621            //
622            // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
623            // instead of having this logic here
624            let (args, typing_env) = match opt_anon_const_kind {
625                // We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
626                // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
627                // about if you have to consider gce whatsoever.
628                Some(ty::AnonConstKind::GCE) => {
629                    if uv.has_non_region_infer() || uv.has_non_region_param() {
630                        // `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
631                        // inference variables and generic parameters to show up in `ty::Const` even though the anon const
632                        // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
633                        match tcx.thir_abstract_const(uv.def) {
634                            Ok(Some(ct)) => {
635                                let ct = tcx.expand_abstract_consts(
636                                    ct.instantiate(tcx, uv.args).skip_norm_wip(),
637                                );
638                                if let Err(e) = ct.error_reported() {
639                                    return Err(EvaluateConstErr::EvaluationFailure(e));
640                                } else if ct.has_non_region_infer() || ct.has_non_region_param() {
641                                    // If the anon const *does* actually use generic parameters or inference variables from
642                                    // the generic arguments provided for it, then we should *not* attempt to evaluate it.
643                                    return Err(EvaluateConstErr::HasGenericsOrInfers);
644                                } else {
645                                    let args =
646                                        replace_param_and_infer_args_with_placeholder(tcx, uv.args);
647                                    let typing_env = infcx
648                                        .typing_env(tcx.erase_and_anonymize_regions(param_env))
649                                        .with_post_analysis_normalized(tcx);
650                                    (args, typing_env)
651                                }
652                            }
653                            Err(_) | Ok(None) => {
654                                let args = GenericArgs::identity_for_item(tcx, uv.def);
655                                let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
656                                (args, typing_env)
657                            }
658                        }
659                    } else {
660                        let typing_env = infcx
661                            .typing_env(tcx.erase_and_anonymize_regions(param_env))
662                            .with_post_analysis_normalized(tcx);
663                        (uv.args, typing_env)
664                    }
665                }
666                Some(ty::AnonConstKind::RepeatExprCount) => {
667                    if uv.has_non_region_infer() {
668                        // Diagnostics will sometimes replace the identity args of anon consts in
669                        // array repeat expr counts with inference variables so we have to handle this
670                        // even though it is not something we should ever actually encounter.
671                        //
672                        // Array repeat expr counts are allowed to syntactically use generic parameters
673                        // but must not actually depend on them in order to evalaute successfully. This means
674                        // that it is actually fine to evalaute them in their own environment rather than with
675                        // the actually provided generic arguments.
676                        tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
677                    }
678
679                    // The generic args of repeat expr counts under `min_const_generics` are not supposed to
680                    // affect evaluation of the constant as this would make it a "truly" generic const arg.
681                    // To prevent this we discard all the generic arguments and evalaute with identity args
682                    // and in its own environment instead of the current environment we are normalizing in.
683                    let args = GenericArgs::identity_for_item(tcx, uv.def);
684                    let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
685
686                    (args, typing_env)
687                }
688                Some(ty::AnonConstKind::GCA)
689                | Some(ty::AnonConstKind::MCG)
690                | Some(ty::AnonConstKind::NonTypeSystem)
691                | None => {
692                    // We are only dealing with "truly" generic/uninferred constants here:
693                    // - GCEConsts have been handled separately
694                    // - Repeat expr count back compat consts have also been handled separately
695                    // So we are free to simply defer evaluation here.
696                    //
697                    // FIXME: This assumes that `args` are normalized which is not necessarily true
698                    //
699                    // Const patterns are converted to type system constants before being
700                    // evaluated. However, we don't care about them here as pattern evaluation
701                    // logic does not go through type system normalization. If it did this would
702                    // be a backwards compatibility problem as we do not enforce "syntactic" non-
703                    // usage of generic parameters like we do here.
704                    if uv.args.has_non_region_param() || uv.args.has_non_region_infer() {
705                        return Err(EvaluateConstErr::HasGenericsOrInfers);
706                    }
707
708                    // Since there is no generic parameter, we can just drop the environment
709                    // to prevent query cycle.
710                    let typing_env = ty::TypingEnv::fully_monomorphized();
711
712                    (uv.args, typing_env)
713                }
714            };
715
716            let uv = ty::UnevaluatedConst::new(uv.def, args);
717            let erased_uv = tcx.erase_and_anonymize_regions(uv);
718
719            use rustc_middle::mir::interpret::ErrorHandled;
720            // FIXME: `def_span` will point at the definition of this const; ideally, we'd point at
721            // where it gets used as a const generic.
722            match tcx.const_eval_resolve_for_typeck(typing_env, erased_uv, tcx.def_span(uv.def)) {
723                Ok(Ok(val)) => Ok(ty::Const::new_value(
724                    tcx,
725                    val,
726                    tcx.type_of(uv.def).instantiate(tcx, uv.args).skip_norm_wip(),
727                )),
728                Ok(Err(_)) => {
729                    let e = tcx.dcx().delayed_bug(
730                        "Type system constant with non valtree'able type evaluated but no error emitted",
731                    );
732                    Err(EvaluateConstErr::InvalidConstParamTy(e))
733                }
734                Err(ErrorHandled::Reported(info, _)) => {
735                    Err(EvaluateConstErr::EvaluationFailure(info.into()))
736                }
737                Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
738            }
739        }
740    }
741}
742
743/// Replaces args that reference param or infer variables with suitable
744/// placeholders. This function is meant to remove these param and infer
745/// args when they're not actually needed to evaluate a constant.
746fn replace_param_and_infer_args_with_placeholder<'tcx>(
747    tcx: TyCtxt<'tcx>,
748    args: GenericArgsRef<'tcx>,
749) -> GenericArgsRef<'tcx> {
750    struct ReplaceParamAndInferWithPlaceholder<'tcx> {
751        tcx: TyCtxt<'tcx>,
752        idx: ty::BoundVar,
753    }
754
755    impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
756        fn cx(&self) -> TyCtxt<'tcx> {
757            self.tcx
758        }
759
760        fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
761            if let ty::Infer(_) = t.kind() {
762                let idx = self.idx;
763                self.idx += 1;
764                Ty::new_placeholder(
765                    self.tcx,
766                    ty::PlaceholderType::new(
767                        ty::UniverseIndex::ROOT,
768                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
769                    ),
770                )
771            } else {
772                t.super_fold_with(self)
773            }
774        }
775
776        fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
777            if let ty::ConstKind::Infer(_) = c.kind() {
778                let idx = self.idx;
779                self.idx += 1;
780                ty::Const::new_placeholder(
781                    self.tcx,
782                    ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)),
783                )
784            } else {
785                c.super_fold_with(self)
786            }
787        }
788    }
789
790    args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
791}
792
793/// Normalizes the predicates and checks whether they hold in an empty environment. If this
794/// returns true, then either normalize encountered an error or one of the predicates did not
795/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
796/// used during analysis.
797pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause<'tcx>>) -> bool {
798    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:798",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(798u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("impossible_predicates(predicates={0:?})",
                                                    predicates) as &dyn Value))])
            });
    } else { ; }
};debug!("impossible_predicates(predicates={:?})", predicates);
799    let (infcx, param_env) = tcx
800        .infer_ctxt()
801        .with_next_trait_solver(true)
802        .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
803
804    let ocx = ObligationCtxt::new(&infcx);
805    let predicates =
806        ocx.normalize(&ObligationCause::dummy(), param_env, Unnormalized::new_wip(predicates));
807    for predicate in predicates {
808        let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
809        ocx.register_obligation(obligation);
810    }
811
812    // Use `try_evaluate_obligations` to only return impossible for true errors,
813    // and not ambiguities or overflows. Since the new trait solver forces
814    // some currently undetected overlap between `dyn Trait: Trait` built-in
815    // vs user-written impls to AMBIGUOUS, this may return ambiguity even
816    // with no infer vars. There may also be ways to encounter ambiguity due
817    // to post-mono overflow.
818    let true_errors = ocx.try_evaluate_obligations();
819    if !true_errors.is_empty() {
820        return true;
821    }
822
823    false
824}
825
826fn instantiate_and_check_impossible_predicates<'tcx>(
827    tcx: TyCtxt<'tcx>,
828    key: (DefId, GenericArgsRef<'tcx>),
829) -> bool {
830    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:830",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(830u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_predicates(key={0:?})",
                                                    key) as &dyn Value))])
            });
    } else { ; }
};debug!("instantiate_and_check_impossible_predicates(key={:?})", key);
831
832    let mut predicates: Vec<_> = tcx
833        .predicates_of(key.0)
834        .instantiate(tcx, key.1)
835        .predicates
836        .into_iter()
837        .map(Unnormalized::skip_norm_wip)
838        .collect();
839
840    // Specifically check trait fulfillment to avoid an error when trying to resolve
841    // associated items.
842    if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
843        let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
844        predicates.push(trait_ref.upcast(tcx));
845    }
846
847    predicates.retain(|predicate| !predicate.has_param());
848    let result = impossible_predicates(tcx, predicates);
849
850    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:850",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(850u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_predicates(key={0:?}) = {1:?}",
                                                    key, result) as &dyn Value))])
            });
    } else { ; }
};debug!("instantiate_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
851    result
852}
853
854/// Checks whether a trait's associated item is impossible to reference on a given impl.
855///
856/// This only considers predicates that reference the impl's generics, and not
857/// those that reference the method's generics.
858fn is_impossible_associated_item(
859    tcx: TyCtxt<'_>,
860    (impl_def_id, trait_item_def_id): (DefId, DefId),
861) -> bool {
862    struct ReferencesOnlyParentGenerics<'tcx> {
863        tcx: TyCtxt<'tcx>,
864        generics: &'tcx ty::Generics,
865        trait_item_def_id: DefId,
866    }
867    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
868        type Result = ControlFlow<()>;
869        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
870            // If this is a parameter from the trait item's own generics, then bail
871            if let ty::Param(param) = *t.kind()
872                && let param_def_id = self.generics.type_param(param, self.tcx).def_id
873                && self.tcx.parent(param_def_id) == self.trait_item_def_id
874            {
875                return ControlFlow::Break(());
876            }
877            t.super_visit_with(self)
878        }
879        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
880            if let ty::ReEarlyParam(param) = r.kind()
881                && let param_def_id = self.generics.region_param(param, self.tcx).def_id
882                && self.tcx.parent(param_def_id) == self.trait_item_def_id
883            {
884                return ControlFlow::Break(());
885            }
886            ControlFlow::Continue(())
887        }
888        fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
889            if let ty::ConstKind::Param(param) = ct.kind()
890                && let param_def_id = self.generics.const_param(param, self.tcx).def_id
891                && self.tcx.parent(param_def_id) == self.trait_item_def_id
892            {
893                return ControlFlow::Break(());
894            }
895            ct.super_visit_with(self)
896        }
897    }
898
899    let generics = tcx.generics_of(trait_item_def_id);
900    let predicates = tcx.predicates_of(trait_item_def_id);
901
902    // Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
903    // since that method *may* have some substitutions where the predicates hold.
904    //
905    // This replicates the logic we use in coherence.
906    let infcx = tcx
907        .infer_ctxt()
908        .ignoring_regions()
909        .with_next_trait_solver(true)
910        .build(TypingMode::Coherence);
911    let param_env = ty::ParamEnv::empty();
912    let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
913
914    let impl_trait_ref =
915        tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args).skip_norm_wip();
916
917    let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
918    let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
919        pred.visit_with(&mut visitor).is_continue().then(|| {
920            Obligation::new(
921                tcx,
922                ObligationCause::dummy_with_span(*span),
923                param_env,
924                ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args).skip_norm_wip(),
925            )
926        })
927    });
928
929    let ocx = ObligationCtxt::new(&infcx);
930    ocx.register_obligations(predicates_for_trait);
931    !ocx.try_evaluate_obligations().is_empty()
932}
933
934pub fn provide(providers: &mut Providers) {
935    dyn_compatibility::provide(providers);
936    vtable::provide(providers);
937    *providers = Providers {
938        specialization_graph_of: specialize::specialization_graph_provider,
939        specializes: specialize::specializes,
940        specialization_enabled_in: specialize::specialization_enabled_in,
941        instantiate_and_check_impossible_predicates,
942        is_impossible_associated_item,
943        ..*providers
944    };
945}