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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: _ = loop {};
            return __tracing_attr_fake_return;
        }
        {
            generic_bounds.into_iter().enumerate().map(move
                    |(idx, (clause, span))|
                    Obligation {
                        cause: cause(idx, span),
                        recursion_depth: 0,
                        param_env,
                        predicate: normalize_clause(clause).as_predicate(),
                    })
        }
    }
}#[instrument(level = "debug", skip(cause, param_env, normalize_clause))]
191pub fn predicates_for_generics<'tcx>(
192    cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
193    mut normalize_clause: impl FnMut(Unnormalized<'tcx, Clause<'tcx>>) -> Clause<'tcx>,
194    param_env: ty::ParamEnv<'tcx>,
195    generic_bounds: ty::InstantiatedClauses<'tcx>,
196) -> impl Iterator<Item = PredicateObligation<'tcx>> {
197    generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
198        cause: cause(idx, span),
199        recursion_depth: 0,
200        param_env,
201        predicate: normalize_clause(clause).as_predicate(),
202    })
203}
204
205/// Determines whether the type `ty` is known to meet `bound` and
206/// returns true if so. Returns false if `ty` either does not meet
207/// `bound` or is not known to meet bound (note that this is
208/// conservative towards *no impl*, which is the opposite of the
209/// `evaluate` methods).
210pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
211    infcx: &InferCtxt<'tcx>,
212    param_env: ty::ParamEnv<'tcx>,
213    ty: Ty<'tcx>,
214    def_id: DefId,
215) -> bool {
216    let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
217    pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
218}
219
220/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
221///
222/// Ping me on zulip if you want to use this method and need help with finding
223/// an appropriate replacement.
224{}
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("pred_known_to_hold_modulo_regions",
                                "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(224u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                ::tracing_core::field::FieldSet::new(&[],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{ meta.fields().value_set_all(&[]) })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: bool = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let obligation =
                            Obligation::new(infcx.tcx, ObligationCause::dummy(),
                                param_env, pred);
                        let result =
                            infcx.evaluate_obligation_no_overflow(&obligation);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:233",
                                                "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(233u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("result")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("result");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if result.must_apply_modulo_regions() {
                            true
                        } else if result.may_apply() && !infcx.next_trait_solver() {
                            let goal =
                                infcx.deeply_resolve_ignoring_regions((obligation.predicate,
                                        obligation.param_env));
                            infcx.probe(|_|
                                    {
                                        let ocx = ObligationCtxt::new(infcx);
                                        ocx.register_obligation(obligation);
                                        let errors = ocx.evaluate_obligations_error_on_ambiguity();
                                        match errors {
                                            TraitErrors::NoErrors =>
                                                infcx.deeply_resolve_ignoring_regions(goal) == goal,
                                            TraitErrors::HasErrors(errors) => {
                                                {
                                                    use ::tracing::__macro_support::Callsite as _;
                                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                        {
                                                            static META: ::tracing::Metadata<'static> =
                                                                {
                                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:254",
                                                                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/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(&[{
                                                                                            const NAME:
                                                                                                ::tracing::__macro_support::FieldName<{
                                                                                                    ::tracing::__macro_support::FieldName::len("errors")
                                                                                                }> =
                                                                                                ::tracing::__macro_support::FieldName::new("errors");
                                                                                            NAME.as_str()
                                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                        ::tracing::metadata::Kind::EVENT)
                                                                };
                                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                                        };
                                                    let enabled =
                                                        ::tracing::Level::DEBUG <=
                                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                                ::tracing::Level::DEBUG <=
                                                                    ::tracing::level_filters::LevelFilter::current() &&
                                                            {
                                                                let interest = __CALLSITE.interest();
                                                                !interest.is_never() &&
                                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                        interest)
                                                            };
                                                    if enabled {
                                                        (|value_set: ::tracing::field::ValueSet|
                                                                    {
                                                                        let meta = __CALLSITE.metadata();
                                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                                        ;
                                                                    })({
                                                                #[allow(unused_imports)]
                                                                use ::tracing::field::{debug, display, Value};
                                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errors)
                                                                                            as &dyn ::tracing::field::Value))])
                                                            });
                                                    } else { ; }
                                                };
                                                false
                                            }
                                        }
                                    })
                        } else { false }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:224",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(224u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
225fn pred_known_to_hold_modulo_regions<'tcx>(
226    infcx: &InferCtxt<'tcx>,
227    param_env: ty::ParamEnv<'tcx>,
228    pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
229) -> bool {
230    let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
231
232    let result = infcx.evaluate_obligation_no_overflow(&obligation);
233    debug!(?result);
234
235    if result.must_apply_modulo_regions() {
236        true
237    } else if result.may_apply() && !infcx.next_trait_solver() {
238        // Sometimes obligations are ambiguous because the recursive evaluator
239        // is not smart enough, so we fall back to fulfillment when we're not certain
240        // that an obligation holds or not. Even still, we must make sure that
241        // the we do no inference in the process of checking this obligation.
242        let goal =
243            infcx.deeply_resolve_ignoring_regions((obligation.predicate, obligation.param_env));
244        infcx.probe(|_| {
245            let ocx = ObligationCtxt::new(infcx);
246            ocx.register_obligation(obligation);
247
248            let errors = ocx.evaluate_obligations_error_on_ambiguity();
249            match errors {
250                // Only known to hold if we did no inference.
251                TraitErrors::NoErrors => infcx.deeply_resolve_ignoring_regions(goal) == goal,
252
253                TraitErrors::HasErrors(errors) => {
254                    debug!(?errors);
255                    false
256                }
257            }
258        })
259    } else {
260        false
261    }
262}
263
264fn set_projection_term_to_non_rigid<'tcx>(
265    tcx: TyCtxt<'tcx>,
266    predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
267) -> impl Iterator<Item = ty::Clause<'tcx>> {
268    predicates.into_iter().map(move |clause| {
269        if let ty::ClauseKind::Projection(projection_pred) = clause.kind().skip_binder() {
270            clause
271                .kind()
272                .rebind(ty::ProjectionClause {
273                    projection_term: projection_pred.projection_term,
274                    term: ty::set_aliases_to_non_rigid(tcx, projection_pred.term).skip_norm_wip(),
275                })
276                .upcast(tcx)
277        } else {
278            clause
279        }
280    })
281}
282
283enum ReplaceRegions {
284    Yes,
285    No,
286}
287
288fn replace_infer_and_non_rigid_alias_with_error<'tcx, T>(
289    infcx: &InferCtxt<'tcx>,
290    value: T,
291    guar: ErrorGuaranteed,
292    replace_regions: ReplaceRegions,
293) -> T
294where
295    T: TypeFoldable<TyCtxt<'tcx>>,
296{
297    let tcx = infcx.tcx;
298    value.fold_with(&mut BottomUpFolder {
299        tcx,
300        ty_op: |ty| {
301            let ty = infcx.shallow_resolve(ty);
302            match ty.kind() {
303                ty::Infer(ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_)) => {
304                    Ty::new_error(tcx, guar)
305                }
306                ty::Alias(ty::IsRigid::No, _) if tcx.next_trait_solver_globally() => {
307                    Ty::new_error(tcx, guar)
308                }
309                _ => ty,
310            }
311        },
312        lt_op: |lt| match replace_regions {
313            // We can't resolve regions using lexical resolution here since
314            // that's private. It probably doesn't matter since we already
315            // got more severe error.
316            ReplaceRegions::Yes => match lt.kind() {
317                ty::ReVar(_) => ty::Region::new_error(tcx, guar),
318                _ => lt,
319            },
320            ReplaceRegions::No => lt,
321        },
322        ct_op: |ct| {
323            let ct = infcx.shallow_resolve_const(ct);
324            match ct.kind() {
325                ty::ConstKind::Infer(ty::InferConst::Var(_)) => ty::Const::new_error(tcx, guar),
326                ty::ConstKind::Alias(ty::IsRigid::No, _) if tcx.next_trait_solver_globally() => {
327                    ty::Const::new_error(tcx, guar)
328                }
329                _ => ct,
330            }
331        },
332    })
333}
334
335{}
#[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_clauses",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(335u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("elaborated_env_clauses")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("elaborated_env_clauses");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("clauses")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("clauses");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&elaborated_env_clauses)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clauses)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Vec<ty::Clause<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                {
                    match (&ty::ParamEnv::new(tcx,
                                    elaborated_env_clauses.iter().copied()), &elaborated_env) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            let infcx =
                tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let elaborated_env =
                if tcx.next_trait_solver_globally() &&
                        !tcx.disable_param_env_normalization_hack() {
                    let elaborated_env =
                        ty::set_type_aliases_to_rigid(tcx, elaborated_env_clauses);
                    let elaborated_env =
                        set_projection_term_to_non_rigid(tcx, elaborated_env);
                    ty::ParamEnv::new(tcx, elaborated_env)
                } else { elaborated_env };
            let clauses =
                ocx.normalize(&cause, elaborated_env,
                    Unnormalized::new_wip(clauses));
            let clauses =
                if tcx.next_trait_solver_globally() {
                    if !tcx.disable_param_env_normalization_hack() {
                        let clauses: Vec<_> =
                            set_projection_term_to_non_rigid(tcx, clauses).collect();
                        ty::set_opaques_to_non_rigid(tcx, clauses).skip_norm_wip()
                    } else {
                        ty::set_aliases_to_non_rigid(tcx, clauses).skip_norm_wip()
                    }
                } else { clauses };
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            let clauses =
                if let TraitErrors::HasErrors(errors) = errors {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:399",
                                            "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(399u32),
                                            ::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};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("do_normalize_clauses: failed to normalize clauses")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let guar =
                        infcx.err_ctxt().report_fulfillment_errors(errors);
                    replace_infer_and_non_rigid_alias_with_error(&infcx,
                        clauses, guar, ReplaceRegions::No)
                } else { clauses };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:406",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(406u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("do_normalize_clauses: normalized clauses = {0:?}",
                                                                clauses) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let normalized_env =
                ty::ParamEnv::new(tcx, clauses.iter().copied());
            let _errors =
                infcx.resolve_regions(cause.body_def_id, normalized_env, []);
            match infcx.deeply_resolve_via_region_graph(clauses.clone()) {
                Ok(clauses) => clauses,
                Err(fixup_err) => {
                    let guar =
                        tcx.dcx().span_delayed_bug(cause.span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("inference variables in normalized parameter environment: {0}",
                                            fixup_err))
                                }));
                    replace_infer_and_non_rigid_alias_with_error(&infcx,
                        clauses, guar, ReplaceRegions::Yes)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, elaborated_env))]
336fn do_normalize_clauses<'tcx>(
337    tcx: TyCtxt<'tcx>,
338    cause: ObligationCause<'tcx>,
339    elaborated_env: ty::ParamEnv<'tcx>,
340    elaborated_env_clauses: Vec<ty::Clause<'tcx>>,
341    clauses: Vec<ty::Clause<'tcx>>,
342) -> Vec<ty::Clause<'tcx>> {
343    // sanity check: it's a perf optimization to ask for a `ParamEnv` *and*
344    // an equivalent list of clauses here to avoid a decompression. In debug
345    // mode we ensure that no callsite accidentally passed in mismatching clauses.
346    debug_assert_eq!(
347        ty::ParamEnv::new(tcx, elaborated_env_clauses.iter().copied()),
348        elaborated_env
349    );
350
351    // FIXME. We should really... do something with these region
352    // obligations. But this call just continues the older
353    // behavior (i.e., doesn't cause any new bugs), and it would
354    // take some further refactoring to actually solve them. In
355    // particular, we would have to handle implied bounds
356    // properly, and that code is currently largely confined to
357    // regionck (though I made some efforts to extract it
358    // out). -nmatsakis
359    //
360    // @arielby: In any case, these obligations are checked
361    // by wfcheck anyway, so I'm not sure we have to check
362    // them here too, and we will remove this function when
363    // we move over to lazy normalization *anyway*.
364    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
365    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
366    // FIXME: `elaborated_env` is not really rigid. We do this to be
367    // consistent with the old solver.
368    let elaborated_env =
369        if tcx.next_trait_solver_globally() && !tcx.disable_param_env_normalization_hack() {
370            let elaborated_env = ty::set_type_aliases_to_rigid(tcx, elaborated_env_clauses);
371            let elaborated_env = set_projection_term_to_non_rigid(tcx, elaborated_env);
372
373            ty::ParamEnv::new(tcx, elaborated_env)
374        } else {
375            elaborated_env
376        };
377    let clauses = ocx.normalize(&cause, elaborated_env, Unnormalized::new_wip(clauses));
378    let clauses = if tcx.next_trait_solver_globally() {
379        if !tcx.disable_param_env_normalization_hack() {
380            let clauses: Vec<_> = set_projection_term_to_non_rigid(tcx, clauses).collect();
381            // FIXME(type_alias_impl_trait): opaque types in param env might be
382            // in defining scope but we're using non body analysis here.
383            // So the rigidness marker is wrong.
384            ty::set_opaques_to_non_rigid(tcx, clauses).skip_norm_wip()
385        } else {
386            // Param env is used in different typing modes but itself
387            // is normalized in `non_body_analysis`.
388            // That not only makes the rigidness of opaques types wrong,
389            // other aliases can be indirectly affected as well.
390            // So we conservatively set everything to be non-rigid.
391            ty::set_aliases_to_non_rigid(tcx, clauses).skip_norm_wip()
392        }
393    } else {
394        clauses
395    };
396
397    let errors = ocx.evaluate_obligations_error_on_ambiguity();
398    let clauses = if let TraitErrors::HasErrors(errors) = errors {
399        debug!("do_normalize_clauses: failed to normalize clauses");
400        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
401        replace_infer_and_non_rigid_alias_with_error(&infcx, clauses, guar, ReplaceRegions::No)
402    } else {
403        clauses
404    };
405
406    debug!("do_normalize_clauses: normalized clauses = {:?}", clauses);
407
408    // FIXME: It's very weird that we ignore region obligations but apparently
409    // still need to use `resolve_regions` as we need the resolved regions in
410    // the normalized clauses.
411    //
412    // FIXME(-Zhigher-ranked-assumptions): We're ignoring region errors for now.
413    // There're placeholder constraints `leaking` out. This is a hack to work around
414    // the fact that we don't support placeholder assumptions right now and is necessary
415    // for `compare_method_clause_entailment`. We should remove this once we have proper
416    // support for implied bounds on binders.
417    //
418    // This ignoring is required by trait-system-refactor-initiative#166. The new solver encounters
419    // this more frequently as we entirely ignore outlives clauses with the old solver.
420    //
421    // FIXME: We should avoid interning clauses both here and at the
422    // caller sites. We should also avoid cloning if possible.
423    let normalized_env = ty::ParamEnv::new(tcx, clauses.iter().copied());
424    let _errors = infcx.resolve_regions(cause.body_def_id, normalized_env, []);
425    match infcx.deeply_resolve_via_region_graph(clauses.clone()) {
426        Ok(clauses) => clauses,
427        Err(fixup_err) => {
428            // The first folder only replaces infers from normalization failure. We might not have
429            // normalization failure and have unconstrained ty/const vars from ill-formed impls.
430            // See `tests/ui/traits/normalize/self-referential-param-env-normalization.rs`.
431            //
432            // We delay a bug here instead of immediately ICEing and let type checking report the
433            // actual user-facing errors.
434            let guar = tcx.dcx().span_delayed_bug(
435                cause.span,
436                format!("inference variables in normalized parameter environment: {fixup_err}"),
437            );
438
439            // This is slightly wrong as we replace opaques with errors.
440            //
441            // We still need to replace regions because `fully_resolve` eagerly returns `Err` if
442            // it encounters unconstrained ty/const var. Thus region vars might not get replaced.
443            replace_infer_and_non_rigid_alias_with_error(&infcx, clauses, guar, ReplaceRegions::Yes)
444        }
445    }
446}
447
448// FIXME: this is gonna need to be removed ...
449/// Normalizes the parameter environment, reporting errors if they occur.
450{}
#[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("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(450u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("unnormalized_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("unnormalized_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::ParamEnv<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut clauses: Vec<_> =
                util::elaborate(tcx,
                        unnormalized_env.into_iter().map(|clause|
                                {
                                    if tcx.features().generic_const_exprs() ||
                                            tcx.next_trait_solver_globally() {
                                        return clause;
                                    }
                                    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::Alias(_, alias_const) = c.kind() &&
                                                    #[allow(non_exhaustive_omitted_patterns)] match alias_const.kind
                                                        {
                                                        ty::AliasConstKind::Anon { .. } => true,
                                                        _ => false,
                                                    } {
                                                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
                                        }
                                    }
                                    clause.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 /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:543",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(543u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-clauses={0:?}",
                                                                clauses) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let elaborated_env_clauses = clauses.iter().copied().collect();
            let elaborated_env =
                ty::ParamEnv::new(tcx, clauses.iter().copied());
            if !elaborated_env.has_aliases() { return elaborated_env; }
            let outlives_clauses: Vec<_> =
                clauses.extract_if(..,
                        |clause|
                            {

                                #[allow(non_exhaustive_omitted_patterns)]
                                match clause.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 /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:575",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(575u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: clauses=(non-outlives={0:?}, outlives={1:?})",
                                                                clauses, outlives_clauses) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let non_outlives_clauses =
                do_normalize_clauses(tcx, cause.clone(), elaborated_env,
                    elaborated_env_clauses, clauses);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:582",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(582u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: non-outlives clauses={0:?}",
                                                                non_outlives_clauses) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let outlives_env =
                non_outlives_clauses.iter().chain(&outlives_clauses).cloned();
            let outlives_env_clauses = outlives_env.collect::<Vec<_>>();
            let outlives_env =
                ty::ParamEnv::new(tcx, outlives_env_clauses.iter().copied());
            let outlives_clauses =
                do_normalize_clauses(tcx, cause, outlives_env,
                    outlives_env_clauses, outlives_clauses);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:594",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(594u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: outlives clauses={0:?}",
                                                                outlives_clauses) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut clauses = non_outlives_clauses;
            clauses.extend(outlives_clauses);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:598",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(598u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final clauses={0:?}",
                                                                clauses) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            ty::ParamEnv::new(tcx, clauses)
        }
    }
}#[instrument(level = "debug", skip(tcx))]
451pub fn normalize_param_env_or_error<'tcx>(
452    tcx: TyCtxt<'tcx>,
453    unnormalized_env: Vec<ty::Clause<'tcx>>,
454    cause: ObligationCause<'tcx>,
455) -> ty::ParamEnv<'tcx> {
456    // I'm not wild about reporting errors here; I'd prefer to
457    // have the errors get reported at a defined place (e.g.,
458    // during typeck). Instead I have all parameter
459    // environments, in effect, going through this function
460    // and hence potentially reporting errors. This ensures of
461    // course that we never forget to normalize (the
462    // alternative seemed like it would involve a lot of
463    // manual invocations of this fn -- and then we'd have to
464    // deal with the errors at each of those sites).
465    //
466    // In any case, in practice, typeck constructs all the
467    // parameter environments once for every fn as it goes,
468    // and errors will get reported then; so outside of type inference we
469    // can be sure that no errors should occur.
470    let mut clauses: Vec<_> = util::elaborate(
471        tcx,
472        unnormalized_env.into_iter().map(|clause| {
473            if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
474                return clause;
475            }
476
477            struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
478
479            impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
480                fn cx(&self) -> TyCtxt<'tcx> {
481                    self.0
482                }
483
484                fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
485                    // FIXME(return_type_notation): track binders in this normalizer, as
486                    // `ty::Const::normalize` can only work with properly preserved binders.
487
488                    if c.has_escaping_bound_vars() {
489                        return ty::Const::new_misc_error(self.0);
490                    }
491
492                    // While it is pretty sus to be evaluating things with an empty param env, it
493                    // should actually be okay since without `feature(generic_const_exprs)` the only
494                    // const arguments that have a non-empty param env are array repeat counts. These
495                    // do not appear in the type system though.
496                    if let ty::ConstKind::Alias(_, alias_const) = c.kind()
497                        && matches!(alias_const.kind, ty::AliasConstKind::Anon { .. })
498                    {
499                        let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
500                        let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
501                        // We should never wind up with any `infcx` local state when normalizing anon consts
502                        // under min const generics.
503                        assert!(!c.has_infer() && !c.has_placeholders());
504                        return c;
505                    }
506
507                    c
508                }
509            }
510
511            // This whole normalization step is a hack to work around the fact that
512            // `normalize_param_env_or_error` is fundamentally broken from using an
513            // unnormalized param env with a trait solver that expects the param env
514            // to be normalized.
515            //
516            // When normalizing the param env we can end up evaluating obligations
517            // that have been normalized but can only be proven via a where clause
518            // which is still in its unnormalized form. example:
519            //
520            // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
521            // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
522            // we first normalize obligations before proving them so we end up proving
523            // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
524            // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
525            // we cannot prove `T: Trait<u8>`.
526            //
527            // The same thing is true for const generics- attempting to prove
528            // `T: Trait<ConstKind::Alias(...)>` with the same thing as a where clauses
529            // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
530            // the unnormalized where clause `T: Trait<ConstKind::Alias(...)>`. In order
531            // for the obligation to hold `4` must be equal to `ConstKind::Alias(...)`
532            // but as we do not have lazy norm implemented, equating the two consts fails outright.
533            //
534            // Ideally we would not normalize consts here at all but it is required for backwards
535            // compatibility. Eventually when lazy norm is implemented this can just be removed.
536            // We do not normalize types here as there is no backwards compatibility requirement
537            // for us to do so.
538            clause.fold_with(&mut ConstNormalizer(tcx))
539        }),
540    )
541    .collect();
542
543    debug!("normalize_param_env_or_error: elaborated-clauses={:?}", clauses);
544
545    let elaborated_env_clauses = clauses.iter().copied().collect();
546    let elaborated_env = ty::ParamEnv::new(tcx, clauses.iter().copied());
547    if !elaborated_env.has_aliases() {
548        return elaborated_env;
549    }
550
551    // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
552    // normalization expects its param-env to be already normalized, which means we have
553    // a circularity.
554    //
555    // The way we handle this is by normalizing the param-env inside an unnormalized version
556    // of the param-env, which means that if the param-env contains unnormalized projections,
557    // we'll have some normalization failures. This is unfortunate.
558    //
559    // Lazy normalization would basically handle this by treating just the
560    // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
561    //
562    // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
563    // types, so to make the situation less bad, we normalize all the predicates *but*
564    // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
565    // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
566    //
567    // This works fairly well because trait matching does not actually care about param-env
568    // TypeOutlives clauses - these are normally used by regionck.
569    let outlives_clauses: Vec<_> = clauses
570        .extract_if(.., |clause| {
571            matches!(clause.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
572        })
573        .collect();
574
575    debug!(
576        "normalize_param_env_or_error: clauses=(non-outlives={:?}, outlives={:?})",
577        clauses, outlives_clauses
578    );
579    let non_outlives_clauses =
580        do_normalize_clauses(tcx, cause.clone(), elaborated_env, elaborated_env_clauses, clauses);
581
582    debug!("normalize_param_env_or_error: non-outlives clauses={:?}", non_outlives_clauses);
583
584    // Not sure whether it is better to include the unnormalized TypeOutlives clauses
585    // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
586    // clauses here anyway. Keeping them here anyway because it seems safer.
587    let outlives_env = non_outlives_clauses.iter().chain(&outlives_clauses).cloned();
588    // perf optimization: get the individual clauses of the outlives env into a vec
589    // so we don't have to decompress again.
590    let outlives_env_clauses = outlives_env.collect::<Vec<_>>();
591    let outlives_env = ty::ParamEnv::new(tcx, outlives_env_clauses.iter().copied());
592    let outlives_clauses =
593        do_normalize_clauses(tcx, cause, outlives_env, outlives_env_clauses, outlives_clauses);
594    debug!("normalize_param_env_or_error: outlives clauses={:?}", outlives_clauses);
595
596    let mut clauses = non_outlives_clauses;
597    clauses.extend(outlives_clauses);
598    debug!("normalize_param_env_or_error: final clauses={:?}", clauses);
599    ty::ParamEnv::new(tcx, clauses)
600}
601
602#[derive(#[automatically_derived]impl<E: ::core::fmt::Debug> ::core::fmt::Debug for
    EvaluateConstErr<E> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::HasGenericsOrInfers =>
                ::core::fmt::Formatter::write_str(f, "HasGenericsOrInfers"),
            Self::InvalidConstParamTy(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "InvalidConstParamTy", &__self_0),
            Self::EvaluationFailure(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "EvaluationFailure", &__self_0),
            Self::FailedNormalization(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FailedNormalization", &__self_0),
        }
    }
}Debug)]
603pub enum EvaluateConstErr<E> {
604    /// The constant being evaluated was either a generic parameter or inference variable, *or*,
605    /// some alias const with either generic parameters or inference variables in its
606    /// generic arguments.
607    HasGenericsOrInfers,
608    /// The type this constant evaluated to is not valid for use in const generics. This should
609    /// always result in an error when checking the constant is correctly typed for the parameter
610    /// it is an argument to, so a bug is delayed when encountering this.
611    InvalidConstParamTy(ErrorGuaranteed),
612    /// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
613    /// This is also used when the constant was already tainted by error.
614    EvaluationFailure(ErrorGuaranteed),
615    FailedNormalization(E),
616}
617
618// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
619// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
620// normalization scheme
621/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
622/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
623/// or inference variables)
624///
625/// You should not call this function unless you are implementing normalization itself. Prefer to use
626/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
627pub fn evaluate_const<'tcx>(
628    infcx: &InferCtxt<'tcx>,
629    ct: ty::Const<'tcx>,
630    param_env: ty::ParamEnv<'tcx>,
631) -> ty::Const<'tcx> {
632    match try_evaluate_const(infcx, ct, param_env, |v| Ok::<_, !>(v.skip_norm_wip())) {
633        Ok(ct) => ct,
634        Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
635            ty::Const::new_error(infcx.tcx, e)
636        }
637        Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
638    }
639}
640
641// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
642// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
643// normalization scheme
644/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
645/// or inference variables to succeed in evaluating.
646///
647/// You should not call this function unless you are implementing normalization itself. Prefer to use
648/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
649{}
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("try_evaluate_const",
                                "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(649u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ct")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ct");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("param_env")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("param_env");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                Result<ty::Const<'tcx>, EvaluateConstErr<E>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let tcx = infcx.tcx;
                        let ct = infcx.deeply_resolve_ignoring_regions(ct);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:658",
                                                "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(658u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("ct")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("ct");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        match ct.kind() {
                            ty::ConstKind::Value(..) => Ok(ct),
                            ty::ConstKind::Error(e) =>
                                Err(EvaluateConstErr::EvaluationFailure(e)),
                            ty::ConstKind::Param(_) | ty::ConstKind::Infer(_) |
                                ty::ConstKind::Bound(_, _) | ty::ConstKind::Placeholder(_) |
                                ty::ConstKind::Expr(_) =>
                                Err(EvaluateConstErr::HasGenericsOrInfers),
                            ty::ConstKind::Alias(_, alias_const) => {
                                let opt_anon_const_kind =
                                    match alias_const.kind {
                                        ty::AliasConstKind::Anon { def_id } =>
                                            Some((def_id, tcx.anon_const_kind(def_id))),
                                        _ => None,
                                    };
                                let (args, typing_env) =
                                    match opt_anon_const_kind {
                                        Some((def_id, ty::AnonConstKind::GCE)) => {
                                            if alias_const.has_non_region_infer() ||
                                                    alias_const.has_non_region_param() {
                                                match tcx.thir_abstract_const(def_id) {
                                                    Ok(Some(ct)) => {
                                                        let ct =
                                                            tcx.expand_abstract_consts(ct.instantiate(tcx,
                                                                        alias_const.args).skip_norm_wip());
                                                        if let Err(e) = ct.error_reported() {
                                                            return Err(EvaluateConstErr::EvaluationFailure(e));
                                                        } else if ct.has_non_region_infer() ||
                                                                ct.has_non_region_param() {
                                                            return Err(EvaluateConstErr::HasGenericsOrInfers);
                                                        } else {
                                                            let args =
                                                                replace_param_and_infer_args_with_placeholder(tcx,
                                                                    alias_const.args);
                                                            let ty::PseudoCanonicalInput { typing_env, value: args } =
                                                                infcx.typing_env(tcx.erase_and_anonymize_regions(param_env)).with_post_analysis_normalized_invalidating_rigid_aliases(tcx,
                                                                    args);
                                                            (args, typing_env)
                                                        }
                                                    }
                                                    Err(_) | Ok(None) => {
                                                        let args = GenericArgs::identity_for_item(tcx, def_id);
                                                        let typing_env =
                                                            ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id);
                                                        (args, typing_env)
                                                    }
                                                }
                                            } else {
                                                let ty::PseudoCanonicalInput { typing_env, value: args } =
                                                    infcx.typing_env(tcx.erase_and_anonymize_regions(param_env)).with_post_analysis_normalized_invalidating_rigid_aliases(tcx,
                                                        alias_const.args);
                                                (args, typing_env)
                                            }
                                        }
                                        Some((def_id, ty::AnonConstKind::RepeatExprCount)) => {
                                            if alias_const.has_non_region_infer() {
                                                tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
                                            }
                                            let args = GenericArgs::identity_for_item(tcx, def_id);
                                            let typing_env =
                                                ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id);
                                            (args, typing_env)
                                        }
                                        Some((_,
                                            ty::AnonConstKind::MCG |
                                            ty::AnonConstKind::NonTypeSystemAnon |
                                            ty::AnonConstKind::NonTypeSystemInline)) | None => {
                                            if alias_const.args.has_non_region_param() ||
                                                        alias_const.args.has_non_region_infer() ||
                                                    alias_const.args.has_non_region_placeholders() {
                                                return Err(EvaluateConstErr::HasGenericsOrInfers);
                                            }
                                            let typing_env = ty::TypingEnv::fully_monomorphized();
                                            (alias_const.args, typing_env)
                                        }
                                    };
                                let alias_const =
                                    ty::AliasConst::new(tcx, alias_const.kind, args);
                                let erased_alias_const =
                                    tcx.erase_and_anonymize_regions(alias_const);
                                use rustc_middle::mir::interpret::ErrorHandled;
                                let span = alias_const.kind.def_span(tcx);
                                match tcx.const_eval_resolve_for_typeck(typing_env,
                                        erased_alias_const, span) {
                                    Ok(Ok(val)) => {
                                        let ty =
                                            normalize_ty(alias_const.type_of(tcx)).map_err(EvaluateConstErr::FailedNormalization)?;
                                        Ok(ty::Const::new_value(tcx, val, ty))
                                    }
                                    Ok(Err(_)) => {
                                        let e =
                                            tcx.dcx().delayed_bug("Type system constant with non valtree'able type evaluated but no error emitted");
                                        Err(EvaluateConstErr::InvalidConstParamTy(e))
                                    }
                                    Err(ErrorHandled::Reported(info, _)) => {
                                        Err(EvaluateConstErr::EvaluationFailure(info.into()))
                                    }
                                    Err(ErrorHandled::TooGeneric(_)) =>
                                        Err(EvaluateConstErr::HasGenericsOrInfers),
                                }
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:649",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(649u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(infcx, normalize_ty), ret)]
650pub fn try_evaluate_const<'tcx, E: Debug>(
651    infcx: &InferCtxt<'tcx>,
652    ct: ty::Const<'tcx>,
653    param_env: ty::ParamEnv<'tcx>,
654    normalize_ty: impl FnOnce(Unnormalized<'tcx, Ty<'tcx>>) -> Result<Ty<'tcx>, E>,
655) -> Result<ty::Const<'tcx>, EvaluateConstErr<E>> {
656    let tcx = infcx.tcx;
657    let ct = infcx.deeply_resolve_ignoring_regions(ct);
658    debug!(?ct);
659
660    match ct.kind() {
661        ty::ConstKind::Value(..) => Ok(ct),
662        ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
663        ty::ConstKind::Param(_)
664        | ty::ConstKind::Infer(_)
665        | ty::ConstKind::Bound(_, _)
666        | ty::ConstKind::Placeholder(_)
667        | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
668        ty::ConstKind::Alias(_, alias_const) => {
669            let opt_anon_const_kind = match alias_const.kind {
670                ty::AliasConstKind::Anon { def_id } => Some((def_id, tcx.anon_const_kind(def_id))),
671                _ => None,
672            };
673
674            // Postpone evaluation of constants that depend on generic parameters or
675            // inference variables.
676            //
677            // We use `TypingMode::PostAnalysis` here which is not *technically* correct
678            // to be revealing opaque types here as borrowcheck has not run yet. However,
679            // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
680            // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
681            // As a result we always use a revealed env when resolving the instance to evaluate.
682            //
683            // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
684            // instead of having this logic here
685            let (args, typing_env) = match opt_anon_const_kind {
686                // We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
687                // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
688                // about if you have to consider gce whatsoever.
689                Some((def_id, ty::AnonConstKind::GCE)) => {
690                    if alias_const.has_non_region_infer() || alias_const.has_non_region_param() {
691                        // `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
692                        // inference variables and generic parameters to show up in `ty::Const` even though the anon const
693                        // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
694                        match tcx.thir_abstract_const(def_id) {
695                            Ok(Some(ct)) => {
696                                let ct = tcx.expand_abstract_consts(
697                                    ct.instantiate(tcx, alias_const.args).skip_norm_wip(),
698                                );
699                                if let Err(e) = ct.error_reported() {
700                                    return Err(EvaluateConstErr::EvaluationFailure(e));
701                                } else if ct.has_non_region_infer() || ct.has_non_region_param() {
702                                    // If the anon const *does* actually use generic parameters or inference variables from
703                                    // the generic arguments provided for it, then we should *not* attempt to evaluate it.
704                                    return Err(EvaluateConstErr::HasGenericsOrInfers);
705                                } else {
706                                    let args = replace_param_and_infer_args_with_placeholder(
707                                        tcx,
708                                        alias_const.args,
709                                    );
710                                    let ty::PseudoCanonicalInput { typing_env, value: args } = infcx
711                                        .typing_env(tcx.erase_and_anonymize_regions(param_env))
712                                        .with_post_analysis_normalized_invalidating_rigid_aliases(
713                                            tcx, args,
714                                        );
715                                    (args, typing_env)
716                                }
717                            }
718                            Err(_) | Ok(None) => {
719                                let args = GenericArgs::identity_for_item(tcx, def_id);
720                                let typing_env =
721                                    ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id);
722                                (args, typing_env)
723                            }
724                        }
725                    } else {
726                        let ty::PseudoCanonicalInput { typing_env, value: args } = infcx
727                            .typing_env(tcx.erase_and_anonymize_regions(param_env))
728                            .with_post_analysis_normalized_invalidating_rigid_aliases(
729                                tcx,
730                                alias_const.args,
731                            );
732                        (args, typing_env)
733                    }
734                }
735                Some((def_id, ty::AnonConstKind::RepeatExprCount)) => {
736                    if alias_const.has_non_region_infer() {
737                        // Diagnostics will sometimes replace the identity args of anon consts in
738                        // array repeat expr counts with inference variables so we have to handle this
739                        // even though it is not something we should ever actually encounter.
740                        //
741                        // Array repeat expr counts are allowed to syntactically use generic parameters
742                        // but must not actually depend on them in order to evalaute successfully. This means
743                        // that it is actually fine to evalaute them in their own environment rather than with
744                        // the actually provided generic arguments.
745                        tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
746                    }
747
748                    // The generic args of repeat expr counts under `min_const_generics` are not supposed to
749                    // affect evaluation of the constant as this would make it a "truly" generic const arg.
750                    // To prevent this we discard all the generic arguments and evalaute with identity args
751                    // and in its own environment instead of the current environment we are normalizing in.
752                    let args = GenericArgs::identity_for_item(tcx, def_id);
753                    let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id);
754
755                    (args, typing_env)
756                }
757                Some((
758                    _,
759                    ty::AnonConstKind::MCG
760                    | ty::AnonConstKind::NonTypeSystemAnon
761                    | ty::AnonConstKind::NonTypeSystemInline,
762                ))
763                | None => {
764                    // We are only dealing with "truly" generic/uninferred constants here:
765                    // - GCEConsts have been handled separately
766                    // - Repeat expr count back compat consts have also been handled separately
767                    // So we are free to simply defer evaluation here.
768                    //
769                    // FIXME: This assumes that `args` are normalized which is not necessarily true
770                    //
771                    // Const patterns are converted to type system constants before being
772                    // evaluated. However, we don't care about them here as pattern evaluation
773                    // logic does not go through type system normalization. If it did this would
774                    // be a backwards compatibility problem as we do not enforce "syntactic" non-
775                    // usage of generic parameters like we do here.
776                    if alias_const.args.has_non_region_param()
777                        || alias_const.args.has_non_region_infer()
778                        || alias_const.args.has_non_region_placeholders()
779                    {
780                        return Err(EvaluateConstErr::HasGenericsOrInfers);
781                    }
782
783                    // Since there is no generic parameter, we can just drop the environment
784                    // to prevent query cycle.
785                    let typing_env = ty::TypingEnv::fully_monomorphized();
786
787                    (alias_const.args, typing_env)
788                }
789            };
790
791            let alias_const = ty::AliasConst::new(tcx, alias_const.kind, args);
792            let erased_alias_const = tcx.erase_and_anonymize_regions(alias_const);
793
794            use rustc_middle::mir::interpret::ErrorHandled;
795            // FIXME: `def_span` will point at the definition of this const; ideally, we'd point at
796            // where it gets used as a const generic.
797            let span = alias_const.kind.def_span(tcx);
798            match tcx.const_eval_resolve_for_typeck(typing_env, erased_alias_const, span) {
799                Ok(Ok(val)) => {
800                    let ty = normalize_ty(alias_const.type_of(tcx))
801                        .map_err(EvaluateConstErr::FailedNormalization)?;
802                    Ok(ty::Const::new_value(tcx, val, ty))
803                }
804                Ok(Err(_)) => {
805                    let e = tcx.dcx().delayed_bug(
806                        "Type system constant with non valtree'able type evaluated but no error emitted",
807                    );
808                    Err(EvaluateConstErr::InvalidConstParamTy(e))
809                }
810                Err(ErrorHandled::Reported(info, _)) => {
811                    Err(EvaluateConstErr::EvaluationFailure(info.into()))
812                }
813                Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
814            }
815        }
816    }
817}
818
819/// Replaces args that reference param or infer variables with suitable
820/// placeholders. This function is meant to remove these param and infer
821/// args when they're not actually needed to evaluate a constant.
822fn replace_param_and_infer_args_with_placeholder<'tcx>(
823    tcx: TyCtxt<'tcx>,
824    args: GenericArgs<'tcx>,
825) -> GenericArgs<'tcx> {
826    struct ReplaceParamAndInferWithPlaceholder<'tcx> {
827        tcx: TyCtxt<'tcx>,
828        idx: ty::BoundVar,
829    }
830
831    impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
832        fn cx(&self) -> TyCtxt<'tcx> {
833            self.tcx
834        }
835
836        fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
837            if let ty::Infer(_) = t.kind() {
838                let idx = self.idx;
839                self.idx += 1;
840                Ty::new_placeholder(
841                    self.tcx,
842                    ty::PlaceholderType::new(
843                        ty::UniverseIndex::ROOT,
844                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
845                    ),
846                )
847            } else {
848                t.super_fold_with(self)
849            }
850        }
851
852        fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
853            if let ty::ConstKind::Infer(_) = c.kind() {
854                let idx = self.idx;
855                self.idx += 1;
856                ty::Const::new_placeholder(
857                    self.tcx,
858                    ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)),
859                )
860            } else {
861                c.super_fold_with(self)
862            }
863        }
864    }
865
866    args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
867}
868
869/// Normalizes the clauses and checks whether they hold in an empty environment. If this
870/// returns true, then either normalize encountered an error or one of the clauses did not
871/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
872/// used during analysis.
873pub fn impossible_clauses<'tcx>(tcx: TyCtxt<'tcx>, clauses: Vec<ty::Clause<'tcx>>) -> bool {
874    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:874",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(874u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("impossible_clauses(clauses={0:?})",
                                                    clauses) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("impossible_clauses(clauses={:?})", clauses);
875    let (infcx, param_env) = tcx
876        .infer_ctxt()
877        .with_next_trait_solver(true)
878        .enable_next_solver_overflow_fcw(false)
879        .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
880
881    let ocx = ObligationCtxt::new(&infcx);
882    let clauses =
883        ocx.normalize(&ObligationCause::dummy(), param_env, Unnormalized::new_wip(clauses));
884    for clause in clauses {
885        let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause);
886        ocx.register_obligation(obligation);
887    }
888
889    // Use `try_evaluate_obligations` to only return impossible for true errors,
890    // and not ambiguities or overflows. Since the new trait solver forces
891    // some currently undetected overlap between `dyn Trait: Trait` built-in
892    // vs user-written impls to AMBIGUOUS, this may return ambiguity even
893    // with no infer vars. There may also be ways to encounter ambiguity due
894    // to post-mono overflow.
895    !ocx.try_evaluate_obligations().no_errors()
896}
897
898fn instantiate_and_check_impossible_clauses<'tcx>(
899    tcx: TyCtxt<'tcx>,
900    key: (DefId, GenericArgs<'tcx>),
901) -> bool {
902    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:902",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(902u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_clauses(key={0:?})",
                                                    key) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("instantiate_and_check_impossible_clauses(key={:?})", key);
903
904    let mut clauses: Vec<_> = tcx
905        .clauses_of(key.0)
906        .instantiate(tcx, key.1)
907        .clauses
908        .into_iter()
909        .map(Unnormalized::skip_norm_wip)
910        .collect();
911
912    // Specifically check trait fulfillment to avoid an error when trying to resolve
913    // associated items.
914    if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
915        let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
916        clauses.push(trait_ref.upcast(tcx));
917    }
918
919    clauses.retain(|clause| !clause.has_param());
920    let result = impossible_clauses(tcx, clauses);
921
922    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs:922",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(922u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_clauses(key={0:?}) = {1:?}",
                                                    key, result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("instantiate_and_check_impossible_clauses(key={:?}) = {:?}", key, result);
923    result
924}
925
926/// Checks whether a trait's associated item is impossible to reference on a given impl.
927///
928/// This only considers predicates that reference the impl's generics, and not
929/// those that reference the method's generics.
930fn is_impossible_associated_item(
931    tcx: TyCtxt<'_>,
932    (impl_def_id, trait_item_def_id): (DefId, DefId),
933) -> bool {
934    struct ReferencesOnlyParentGenerics<'tcx> {
935        tcx: TyCtxt<'tcx>,
936        generics: &'tcx ty::Generics,
937        trait_item_def_id: DefId,
938    }
939    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
940        type Result = ControlFlow<()>;
941        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
942            // If this is a parameter from the trait item's own generics, then bail
943            if let ty::Param(param) = *t.kind()
944                && let param_def_id = self.generics.type_param(param, self.tcx).def_id
945                && self.tcx.parent(param_def_id) == self.trait_item_def_id
946            {
947                return ControlFlow::Break(());
948            }
949            t.super_visit_with(self)
950        }
951        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
952            if let ty::ReEarlyParam(param) = r.kind()
953                && let param_def_id = self.generics.region_param(param, self.tcx).def_id
954                && self.tcx.parent(param_def_id) == self.trait_item_def_id
955            {
956                return ControlFlow::Break(());
957            }
958            ControlFlow::Continue(())
959        }
960        fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
961            if let ty::ConstKind::Param(param) = ct.kind()
962                && let param_def_id = self.generics.const_param(param, self.tcx).def_id
963                && self.tcx.parent(param_def_id) == self.trait_item_def_id
964            {
965                return ControlFlow::Break(());
966            }
967            ct.super_visit_with(self)
968        }
969    }
970
971    let generics = tcx.generics_of(trait_item_def_id);
972    let gen_clauses = tcx.clauses_of(trait_item_def_id);
973
974    // Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
975    // since that method *may* have some substitutions where the predicates hold.
976    //
977    // This replicates the logic we use in coherence.
978    let infcx = tcx
979        .infer_ctxt()
980        .ignoring_regions()
981        .with_next_trait_solver(true)
982        .enable_next_solver_overflow_fcw(false)
983        .build(TypingMode::Coherence);
984    let param_env = ty::ParamEnv::empty();
985    let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
986
987    let impl_trait_ref =
988        tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args).skip_norm_wip();
989
990    let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
991    let predicates_for_trait = gen_clauses.clauses.iter().filter_map(|(clause, span)| {
992        clause.visit_with(&mut visitor).is_continue().then(|| {
993            Obligation::new(
994                tcx,
995                ObligationCause::dummy_with_span(*span),
996                param_env,
997                ty::EarlyBinder::bind(tcx, *clause)
998                    .instantiate(tcx, impl_trait_ref.args)
999                    .skip_norm_wip(),
1000            )
1001        })
1002    });
1003
1004    let ocx = ObligationCtxt::new(&infcx);
1005    ocx.register_obligations(predicates_for_trait);
1006    !ocx.try_evaluate_obligations().no_errors()
1007}
1008
1009pub fn provide(providers: &mut Providers) {
1010    dyn_compatibility::provide(providers);
1011    vtable::provide(providers);
1012    *providers = Providers {
1013        specialization_graph_of: specialize::specialization_graph_provider,
1014        specializes: specialize::specializes,
1015        specialization_enabled_in: specialize::specialization_enabled_in,
1016        instantiate_and_check_impossible_clauses,
1017        is_impossible_associated_item,
1018        live_args_for_alias_from_outlives_bounds:
1019            outlives_for_liveness::live_args_for_alias_from_outlives_bounds,
1020        args_known_to_outlive_alias_params:
1021            outlives_for_liveness::args_known_to_outlive_alias_params,
1022        ..*providers
1023    };
1024}