Skip to main content

rustc_trait_selection/traits/
mod.rs

1//! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5pub mod auto_trait;
6pub(crate) mod coherence;
7pub mod const_evaluatable;
8mod dyn_compatibility;
9pub mod effects;
10mod engine;
11mod fulfill;
12pub mod misc;
13pub mod normalize;
14pub mod outlives_bounds;
15pub mod outlives_for_liveness;
16pub mod project;
17pub mod query;
18#[allow(hidden_glob_reexports)]
19mod select;
20pub mod specialize;
21mod structural_normalize;
22#[allow(hidden_glob_reexports)]
23mod util;
24pub mod vtable;
25pub mod wf;
26
27use std::fmt::Debug;
28use std::ops::ControlFlow;
29
30use rustc_errors::ErrorGuaranteed;
31pub use rustc_infer::traits::*;
32use rustc_macros::TypeVisitable;
33use rustc_middle::query::Providers;
34use rustc_middle::ty::error::{ExpectedFound, TypeError};
35use rustc_middle::ty::{
36    self, Clause, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder,
37    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode,
38    Unnormalized, Upcast,
39};
40use rustc_span::Span;
41use rustc_span::def_id::DefId;
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::{ObligationCtxt, TraitEngineExt};
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    sizedness_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]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "FulfillmentError", "obligation", &self.obligation, "code",
            &self.code, "root_obligation", &&self.root_obligation)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for FulfillmentError<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    FulfillmentError {
                        obligation: ref __binding_0,
                        code: ref __binding_1,
                        root_obligation: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
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::Subtype(_, _)
103            | FulfillmentErrorCode::ConstEquate(_, _) => true,
104            FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
105                false
106            }
107        }
108    }
109}
110
111#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FulfillmentErrorCode<'tcx> {
    #[inline]
    fn clone(&self) -> FulfillmentErrorCode<'tcx> {
        match self {
            FulfillmentErrorCode::Cycle(__self_0) =>
                FulfillmentErrorCode::Cycle(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Select(__self_0) =>
                FulfillmentErrorCode::Select(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Project(__self_0) =>
                FulfillmentErrorCode::Project(::core::clone::Clone::clone(__self_0)),
            FulfillmentErrorCode::Subtype(__self_0, __self_1) =>
                FulfillmentErrorCode::Subtype(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            FulfillmentErrorCode::ConstEquate(__self_0, __self_1) =>
                FulfillmentErrorCode::ConstEquate(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            FulfillmentErrorCode::Ambiguity { overflow: __self_0 } =>
                FulfillmentErrorCode::Ambiguity {
                    overflow: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for FulfillmentErrorCode<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    FulfillmentErrorCode::Cycle(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Select(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Project(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Subtype(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::ConstEquate(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    FulfillmentErrorCode::Ambiguity { overflow: ref __binding_0
                        } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
112pub enum FulfillmentErrorCode<'tcx> {
113    /// Inherently impossible to fulfill; this trait is implemented if and only
114    /// if it is already implemented.
115    Cycle(PredicateObligations<'tcx>),
116    Select(SelectionError<'tcx>),
117    Project(MismatchedProjectionTypes<'tcx>),
118    Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
119    ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
120    Ambiguity {
121        /// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
122        /// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
123        /// emitting a fatal error instead.
124        overflow: Option<bool>,
125    },
126}
127
128impl<'tcx> Debug for FulfillmentErrorCode<'tcx> {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        match *self {
131            FulfillmentErrorCode::Select(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
132            FulfillmentErrorCode::Project(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
133            FulfillmentErrorCode::Subtype(ref a, ref b) => {
134                f.write_fmt(format_args!("CodeSubtypeError({0:?}, {1:?})", a, b))write!(f, "CodeSubtypeError({a:?}, {b:?})")
135            }
136            FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
137                f.write_fmt(format_args!("CodeConstEquateError({0:?}, {1:?})", a, b))write!(f, "CodeConstEquateError({a:?}, {b:?})")
138            }
139            FulfillmentErrorCode::Ambiguity { overflow: None } => f.write_fmt(format_args!("Ambiguity"))write!(f, "Ambiguity"),
140            FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
141                f.write_fmt(format_args!("Overflow({0})", suggest_increasing_limit))write!(f, "Overflow({suggest_increasing_limit})")
142            }
143            FulfillmentErrorCode::Cycle(ref cycle) => f.write_fmt(format_args!("Cycle({0:?})", cycle))write!(f, "Cycle({cycle:?})"),
144        }
145    }
146}
147
148/// Whether to skip the leak check, as part of a future compatibility warning step.
149///
150/// The "default" for skip-leak-check corresponds to the current
151/// behavior (do not skip the leak check) -- not the behavior we are
152/// transitioning into.
153#[derive(#[automatically_derived]
impl ::core::marker::Copy for SkipLeakCheck { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SkipLeakCheck {
    #[inline]
    fn clone(&self) -> SkipLeakCheck { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SkipLeakCheck {
    #[inline]
    fn eq(&self, other: &SkipLeakCheck) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SkipLeakCheck {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SkipLeakCheck {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                SkipLeakCheck::Yes => "Yes",
                SkipLeakCheck::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for SkipLeakCheck {
    #[inline]
    fn default() -> SkipLeakCheck { Self::No }
}Default)]
154pub enum SkipLeakCheck {
155    Yes,
156    #[default]
157    No,
158}
159
160impl SkipLeakCheck {
161    fn is_yes(self) -> bool {
162        self == SkipLeakCheck::Yes
163    }
164}
165
166/// The mode that trait queries run in.
167#[derive(#[automatically_derived]
impl ::core::marker::Copy for TraitQueryMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TraitQueryMode {
    #[inline]
    fn clone(&self) -> TraitQueryMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitQueryMode {
    #[inline]
    fn eq(&self, other: &TraitQueryMode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TraitQueryMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for TraitQueryMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TraitQueryMode::Standard => "Standard",
                TraitQueryMode::Canonical => "Canonical",
            })
    }
}Debug)]
168pub enum TraitQueryMode {
169    /// Standard/un-canonicalized queries get accurate
170    /// spans etc. passed in and hence can do reasonable
171    /// error reporting on their own.
172    Standard,
173    /// Canonical queries get dummy spans and hence
174    /// must generally propagate errors to
175    /// pre-canonicalization callsites.
176    Canonical,
177}
178
179/// Creates predicate obligations from the generic bounds.
180#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("predicates_for_generics",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(180u32),
                                    ::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))]
181pub fn predicates_for_generics<'tcx>(
182    cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
183    mut normalize_clause: impl FnMut(Unnormalized<'tcx, Clause<'tcx>>) -> Clause<'tcx>,
184    param_env: ty::ParamEnv<'tcx>,
185    generic_bounds: ty::InstantiatedClauses<'tcx>,
186) -> impl Iterator<Item = PredicateObligation<'tcx>> {
187    generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
188        cause: cause(idx, span),
189        recursion_depth: 0,
190        param_env,
191        predicate: normalize_clause(clause).as_predicate(),
192    })
193}
194
195/// Determines whether the type `ty` is known to meet `bound` and
196/// returns true if so. Returns false if `ty` either does not meet
197/// `bound` or is not known to meet bound (note that this is
198/// conservative towards *no impl*, which is the opposite of the
199/// `evaluate` methods).
200pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
201    infcx: &InferCtxt<'tcx>,
202    param_env: ty::ParamEnv<'tcx>,
203    ty: Ty<'tcx>,
204    def_id: DefId,
205) -> bool {
206    let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
207    pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
208}
209
210/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
211///
212/// Ping me on zulip if you want to use this method and need help with finding
213/// an appropriate replacement.
214x;#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
215fn pred_known_to_hold_modulo_regions<'tcx>(
216    infcx: &InferCtxt<'tcx>,
217    param_env: ty::ParamEnv<'tcx>,
218    pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
219) -> bool {
220    let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
221
222    let result = infcx.evaluate_obligation_no_overflow(&obligation);
223    debug!(?result);
224
225    if result.must_apply_modulo_regions() {
226        true
227    } else if result.may_apply() && !infcx.next_trait_solver() {
228        // Sometimes obligations are ambiguous because the recursive evaluator
229        // is not smart enough, so we fall back to fulfillment when we're not certain
230        // that an obligation holds or not. Even still, we must make sure that
231        // the we do no inference in the process of checking this obligation.
232        let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
233        infcx.probe(|_| {
234            let ocx = ObligationCtxt::new(infcx);
235            ocx.register_obligation(obligation);
236
237            let errors = ocx.evaluate_obligations_error_on_ambiguity();
238            match errors.as_slice() {
239                // Only known to hold if we did no inference.
240                [] => infcx.resolve_vars_if_possible(goal) == goal,
241
242                errors => {
243                    debug!(?errors);
244                    false
245                }
246            }
247        })
248    } else {
249        false
250    }
251}
252
253fn set_projection_term_to_non_rigid<'tcx>(
254    tcx: TyCtxt<'tcx>,
255    predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
256) -> impl Iterator<Item = ty::Clause<'tcx>> {
257    predicates.into_iter().map(move |clause| {
258        if let ty::ClauseKind::Projection(projection_pred) = clause.kind().skip_binder() {
259            clause
260                .kind()
261                .rebind(ty::ProjectionPredicate {
262                    projection_term: projection_pred.projection_term,
263                    term: ty::set_aliases_to_non_rigid(tcx, projection_pred.term).skip_norm_wip(),
264                })
265                .upcast(tcx)
266        } else {
267            clause
268        }
269    })
270}
271
272#[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("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(272u32),
                                    ::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("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(&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:
                    Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = cause.span;
            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);
                    let elaborated_env =
                        set_projection_term_to_non_rigid(tcx,
                            elaborated_env.caller_bounds());
                    ty::ParamEnv::new(tcx.mk_clauses_from_iter(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();
            if !errors.is_empty() {
                let reported =
                    infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(reported);
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:332",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(332u32),
                                    ::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 _errors =
                infcx.resolve_regions(cause.body_def_id, elaborated_env, []);
            match infcx.fully_resolve(clauses) {
                Ok(clauses) => Ok(clauses),
                Err(fixup_err) => {
                    Err(tcx.dcx().span_delayed_bug(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("inference variables in normalized parameter environment: {0}",
                                            fixup_err))
                                })))
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, elaborated_env))]
273fn do_normalize_clauses<'tcx>(
274    tcx: TyCtxt<'tcx>,
275    cause: ObligationCause<'tcx>,
276    elaborated_env: ty::ParamEnv<'tcx>,
277    clauses: Vec<ty::Clause<'tcx>>,
278) -> Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> {
279    // FIXME. We should really... do something with these region
280    // obligations. But this call just continues the older
281    // behavior (i.e., doesn't cause any new bugs), and it would
282    // take some further refactoring to actually solve them. In
283    // particular, we would have to handle implied bounds
284    // properly, and that code is currently largely confined to
285    // regionck (though I made some efforts to extract it
286    // out). -nmatsakis
287    //
288    // @arielby: In any case, these obligations are checked
289    // by wfcheck anyway, so I'm not sure we have to check
290    // them here too, and we will remove this function when
291    // we move over to lazy normalization *anyway*.
292    let span = cause.span;
293    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
294    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
295    // FIXME: `elaborated_env` is not really rigid. We do this to be
296    // consistent with the old solver.
297    let elaborated_env = if tcx.next_trait_solver_globally()
298        && !tcx.disable_param_env_normalization_hack()
299    {
300        let elaborated_env = ty::set_type_aliases_to_rigid(tcx, elaborated_env);
301        let elaborated_env = set_projection_term_to_non_rigid(tcx, elaborated_env.caller_bounds());
302        ty::ParamEnv::new(tcx.mk_clauses_from_iter(elaborated_env))
303    } else {
304        elaborated_env
305    };
306    let clauses = ocx.normalize(&cause, elaborated_env, Unnormalized::new_wip(clauses));
307    let clauses = if tcx.next_trait_solver_globally() {
308        if !tcx.disable_param_env_normalization_hack() {
309            let clauses: Vec<_> = set_projection_term_to_non_rigid(tcx, clauses).collect();
310            // FIXME(type_alias_impl_trait): opaque types in param env might be
311            // in defining scope but we're using non body analysis here.
312            // So the rigidness marker is wrong.
313            ty::set_opaques_to_non_rigid(tcx, clauses).skip_norm_wip()
314        } else {
315            // Param env is used in different typing modes but itself
316            // is normalized in `non_body_analysis`.
317            // That not only makes the rigidness of opaques types wrong,
318            // other aliases can be indirectly affected as well.
319            // So we conservatively set everything to be non-rigid.
320            ty::set_aliases_to_non_rigid(tcx, clauses).skip_norm_wip()
321        }
322    } else {
323        clauses
324    };
325
326    let errors = ocx.evaluate_obligations_error_on_ambiguity();
327    if !errors.is_empty() {
328        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
329        return Err(reported);
330    }
331
332    debug!("do_normalize_clauses: normalized clauses = {:?}", clauses);
333
334    // We can use the `elaborated_env` here; the region code only
335    // cares about declarations like `'a: 'b`.
336    //
337    // FIXME: It's very weird that we ignore region obligations but apparently
338    // still need to use `resolve_regions` as we need the resolved regions in
339    // the normalized predicates.
340    //
341    // FIXME(-Zhigher-ranked-assumptions): We're ignoring region errors for now.
342    // There're placeholder constraints `leaking` out. This is a hack to work around
343    // the fact that we don't support placeholder assumptions right now and is necessary
344    // for `compare_method_predicate_entailment`. We should remove this once we
345    // have proper support for implied bounds on binders.
346    //
347    // This is required by trait-system-refactor-initiative#166. The new solver encounters
348    // this more frequently as we entirely ignore outlives predicates with the old solver.
349    let _errors = infcx.resolve_regions(cause.body_def_id, elaborated_env, []);
350    match infcx.fully_resolve(clauses) {
351        Ok(clauses) => Ok(clauses),
352        Err(fixup_err) => {
353            // If we encounter a fixup error, it means that some type
354            // variable wound up unconstrained. That can happen for
355            // ill-formed impls, so we delay a bug here instead of
356            // immediately ICEing and let type checking report the
357            // actual user-facing errors.
358            Err(tcx.dcx().span_delayed_bug(
359                span,
360                format!("inference variables in normalized parameter environment: {fixup_err}"),
361            ))
362        }
363    }
364}
365
366// FIXME: this is gonna need to be removed ...
367/// Normalizes the parameter environment, reporting errors if they occur.
368#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("normalize_param_env_or_error",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(368u32),
                                    ::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.caller_bounds().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 compiler/rustc_trait_selection/src/traits/mod.rs:461",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(461u32),
                                    ::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 = ty::ParamEnv::new(tcx.mk_clauses(&clauses));
            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 compiler/rustc_trait_selection/src/traits/mod.rs:492",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(492u32),
                                    ::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: predicates=(non-outlives={0:?}, outlives={1:?})",
                                                                clauses, outlives_clauses) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let Ok(non_outlives_clauses) =
                do_normalize_clauses(tcx, cause.clone(), elaborated_env,
                    clauses) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:500",
                                            "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(500u32),
                                            ::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: errored resolving non-outlives clauses")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    return elaborated_env;
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:504",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(504u32),
                                    ::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 =
                ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
            let Ok(outlives_clauses) =
                do_normalize_clauses(tcx, cause, outlives_env,
                    outlives_clauses) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:514",
                                            "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(514u32),
                                            ::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: errored resolving outlives clauses")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    return elaborated_env;
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:517",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(517u32),
                                    ::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 compiler/rustc_trait_selection/src/traits/mod.rs:521",
                                    "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(521u32),
                                    ::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.mk_clauses(&clauses))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
369pub fn normalize_param_env_or_error<'tcx>(
370    tcx: TyCtxt<'tcx>,
371    unnormalized_env: ty::ParamEnv<'tcx>,
372    cause: ObligationCause<'tcx>,
373) -> ty::ParamEnv<'tcx> {
374    // I'm not wild about reporting errors here; I'd prefer to
375    // have the errors get reported at a defined place (e.g.,
376    // during typeck). Instead I have all parameter
377    // environments, in effect, going through this function
378    // and hence potentially reporting errors. This ensures of
379    // course that we never forget to normalize (the
380    // alternative seemed like it would involve a lot of
381    // manual invocations of this fn -- and then we'd have to
382    // deal with the errors at each of those sites).
383    //
384    // In any case, in practice, typeck constructs all the
385    // parameter environments once for every fn as it goes,
386    // and errors will get reported then; so outside of type inference we
387    // can be sure that no errors should occur.
388    let mut clauses: Vec<_> = util::elaborate(
389        tcx,
390        unnormalized_env.caller_bounds().into_iter().map(|clause| {
391            if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
392                return clause;
393            }
394
395            struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
396
397            impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
398                fn cx(&self) -> TyCtxt<'tcx> {
399                    self.0
400                }
401
402                fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
403                    // FIXME(return_type_notation): track binders in this normalizer, as
404                    // `ty::Const::normalize` can only work with properly preserved binders.
405
406                    if c.has_escaping_bound_vars() {
407                        return ty::Const::new_misc_error(self.0);
408                    }
409
410                    // While it is pretty sus to be evaluating things with an empty param env, it
411                    // should actually be okay since without `feature(generic_const_exprs)` the only
412                    // const arguments that have a non-empty param env are array repeat counts. These
413                    // do not appear in the type system though.
414                    if let ty::ConstKind::Alias(_, alias_const) = c.kind()
415                        && matches!(alias_const.kind, ty::AliasConstKind::Anon { .. })
416                    {
417                        let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
418                        let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
419                        // We should never wind up with any `infcx` local state when normalizing anon consts
420                        // under min const generics.
421                        assert!(!c.has_infer() && !c.has_placeholders());
422                        return c;
423                    }
424
425                    c
426                }
427            }
428
429            // This whole normalization step is a hack to work around the fact that
430            // `normalize_param_env_or_error` is fundamentally broken from using an
431            // unnormalized param env with a trait solver that expects the param env
432            // to be normalized.
433            //
434            // When normalizing the param env we can end up evaluating obligations
435            // that have been normalized but can only be proven via a where clause
436            // which is still in its unnormalized form. example:
437            //
438            // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
439            // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
440            // we first normalize obligations before proving them so we end up proving
441            // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
442            // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
443            // we cannot prove `T: Trait<u8>`.
444            //
445            // The same thing is true for const generics- attempting to prove
446            // `T: Trait<ConstKind::Alias(...)>` with the same thing as a where clauses
447            // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
448            // the unnormalized where clause `T: Trait<ConstKind::Alias(...)>`. In order
449            // for the obligation to hold `4` must be equal to `ConstKind::Alias(...)`
450            // but as we do not have lazy norm implemented, equating the two consts fails outright.
451            //
452            // Ideally we would not normalize consts here at all but it is required for backwards
453            // compatibility. Eventually when lazy norm is implemented this can just be removed.
454            // We do not normalize types here as there is no backwards compatibility requirement
455            // for us to do so.
456            clause.fold_with(&mut ConstNormalizer(tcx))
457        }),
458    )
459    .collect();
460
461    debug!("normalize_param_env_or_error: elaborated-clauses={:?}", clauses);
462
463    let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&clauses));
464    if !elaborated_env.has_aliases() {
465        return elaborated_env;
466    }
467
468    // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
469    // normalization expects its param-env to be already normalized, which means we have
470    // a circularity.
471    //
472    // The way we handle this is by normalizing the param-env inside an unnormalized version
473    // of the param-env, which means that if the param-env contains unnormalized projections,
474    // we'll have some normalization failures. This is unfortunate.
475    //
476    // Lazy normalization would basically handle this by treating just the
477    // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
478    //
479    // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
480    // types, so to make the situation less bad, we normalize all the predicates *but*
481    // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
482    // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
483    //
484    // This works fairly well because trait matching does not actually care about param-env
485    // TypeOutlives predicates - these are normally used by regionck.
486    let outlives_clauses: Vec<_> = clauses
487        .extract_if(.., |clause| {
488            matches!(clause.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
489        })
490        .collect();
491
492    debug!(
493        "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
494        clauses, outlives_clauses
495    );
496    let Ok(non_outlives_clauses) =
497        do_normalize_clauses(tcx, cause.clone(), elaborated_env, clauses)
498    else {
499        // An unnormalized env is better than nothing.
500        debug!("normalize_param_env_or_error: errored resolving non-outlives clauses");
501        return elaborated_env;
502    };
503
504    debug!("normalize_param_env_or_error: non-outlives clauses={:?}", non_outlives_clauses);
505
506    // Not sure whether it is better to include the unnormalized TypeOutlives predicates
507    // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
508    // predicates here anyway. Keeping them here anyway because it seems safer.
509    let outlives_env = non_outlives_clauses.iter().chain(&outlives_clauses).cloned();
510    let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
511    let Ok(outlives_clauses) = do_normalize_clauses(tcx, cause, outlives_env, outlives_clauses)
512    else {
513        // An unnormalized env is better than nothing.
514        debug!("normalize_param_env_or_error: errored resolving outlives clauses");
515        return elaborated_env;
516    };
517    debug!("normalize_param_env_or_error: outlives clauses={:?}", outlives_clauses);
518
519    let mut clauses = non_outlives_clauses;
520    clauses.extend(outlives_clauses);
521    debug!("normalize_param_env_or_error: final clauses={:?}", clauses);
522    ty::ParamEnv::new(tcx.mk_clauses(&clauses))
523}
524
525#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EvaluateConstErr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            EvaluateConstErr::HasGenericsOrInfers =>
                ::core::fmt::Formatter::write_str(f, "HasGenericsOrInfers"),
            EvaluateConstErr::InvalidConstParamTy(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "InvalidConstParamTy", &__self_0),
            EvaluateConstErr::EvaluationFailure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "EvaluationFailure", &__self_0),
        }
    }
}Debug)]
526pub enum EvaluateConstErr {
527    /// The constant being evaluated was either a generic parameter or inference variable, *or*,
528    /// some alias const with either generic parameters or inference variables in its
529    /// generic arguments.
530    HasGenericsOrInfers,
531    /// The type this constant evaluated to is not valid for use in const generics. This should
532    /// always result in an error when checking the constant is correctly typed for the parameter
533    /// it is an argument to, so a bug is delayed when encountering this.
534    InvalidConstParamTy(ErrorGuaranteed),
535    /// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
536    /// This is also used when the constant was already tainted by error.
537    EvaluationFailure(ErrorGuaranteed),
538}
539
540// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
541// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
542// normalization scheme
543/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
544/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
545/// or inference variables)
546///
547/// You should not call this function unless you are implementing normalization itself. Prefer to use
548/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
549pub fn evaluate_const<'tcx>(
550    infcx: &InferCtxt<'tcx>,
551    ct: ty::Const<'tcx>,
552    param_env: ty::ParamEnv<'tcx>,
553) -> ty::Const<'tcx> {
554    match try_evaluate_const(infcx, ct, param_env) {
555        Ok(ct) => ct,
556        Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
557            ty::Const::new_error(infcx.tcx, e)
558        }
559        Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
560    }
561}
562
563// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
564// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
565// normalization scheme
566/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
567/// or inference variables to succeed in evaluating.
568///
569/// You should not call this function unless you are implementing normalization itself. Prefer to use
570/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
571x;#[instrument(level = "debug", skip(infcx), ret)]
572pub fn try_evaluate_const<'tcx>(
573    infcx: &InferCtxt<'tcx>,
574    ct: ty::Const<'tcx>,
575    param_env: ty::ParamEnv<'tcx>,
576) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
577    let tcx = infcx.tcx;
578    let ct = infcx.resolve_vars_if_possible(ct);
579    debug!(?ct);
580
581    match ct.kind() {
582        ty::ConstKind::Value(..) => Ok(ct),
583        ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
584        ty::ConstKind::Param(_)
585        | ty::ConstKind::Infer(_)
586        | ty::ConstKind::Bound(_, _)
587        | ty::ConstKind::Placeholder(_)
588        | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
589        ty::ConstKind::Alias(_, alias_const) => {
590            let opt_anon_const_kind = match alias_const.kind {
591                ty::AliasConstKind::Anon { def_id } => Some((def_id, tcx.anon_const_kind(def_id))),
592                _ => None,
593            };
594
595            // Postpone evaluation of constants that depend on generic parameters or
596            // inference variables.
597            //
598            // We use `TypingMode::PostAnalysis` here which is not *technically* correct
599            // to be revealing opaque types here as borrowcheck has not run yet. However,
600            // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
601            // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
602            // As a result we always use a revealed env when resolving the instance to evaluate.
603            //
604            // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
605            // instead of having this logic here
606            let (args, typing_env) = match opt_anon_const_kind {
607                // We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
608                // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
609                // about if you have to consider gce whatsoever.
610                Some((def_id, ty::AnonConstKind::GCE)) => {
611                    if alias_const.has_non_region_infer() || alias_const.has_non_region_param() {
612                        // `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
613                        // inference variables and generic parameters to show up in `ty::Const` even though the anon const
614                        // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
615                        match tcx.thir_abstract_const(def_id) {
616                            Ok(Some(ct)) => {
617                                let ct = tcx.expand_abstract_consts(
618                                    ct.instantiate(tcx, alias_const.args).skip_norm_wip(),
619                                );
620                                if let Err(e) = ct.error_reported() {
621                                    return Err(EvaluateConstErr::EvaluationFailure(e));
622                                } else if ct.has_non_region_infer() || ct.has_non_region_param() {
623                                    // If the anon const *does* actually use generic parameters or inference variables from
624                                    // the generic arguments provided for it, then we should *not* attempt to evaluate it.
625                                    return Err(EvaluateConstErr::HasGenericsOrInfers);
626                                } else {
627                                    let args = replace_param_and_infer_args_with_placeholder(
628                                        tcx,
629                                        alias_const.args,
630                                    );
631                                    let typing_env = infcx
632                                        .typing_env(tcx.erase_and_anonymize_regions(param_env))
633                                        .with_post_analysis_normalized(tcx);
634                                    (args, typing_env)
635                                }
636                            }
637                            Err(_) | Ok(None) => {
638                                let args = GenericArgs::identity_for_item(tcx, def_id);
639                                let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
640                                (args, typing_env)
641                            }
642                        }
643                    } else {
644                        let typing_env = infcx
645                            .typing_env(tcx.erase_and_anonymize_regions(param_env))
646                            .with_post_analysis_normalized(tcx);
647                        (alias_const.args, typing_env)
648                    }
649                }
650                Some((def_id, ty::AnonConstKind::RepeatExprCount)) => {
651                    if alias_const.has_non_region_infer() {
652                        // Diagnostics will sometimes replace the identity args of anon consts in
653                        // array repeat expr counts with inference variables so we have to handle this
654                        // even though it is not something we should ever actually encounter.
655                        //
656                        // Array repeat expr counts are allowed to syntactically use generic parameters
657                        // but must not actually depend on them in order to evalaute successfully. This means
658                        // that it is actually fine to evalaute them in their own environment rather than with
659                        // the actually provided generic arguments.
660                        tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
661                    }
662
663                    // The generic args of repeat expr counts under `min_const_generics` are not supposed to
664                    // affect evaluation of the constant as this would make it a "truly" generic const arg.
665                    // To prevent this we discard all the generic arguments and evalaute with identity args
666                    // and in its own environment instead of the current environment we are normalizing in.
667                    let args = GenericArgs::identity_for_item(tcx, def_id);
668                    let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
669
670                    (args, typing_env)
671                }
672                Some((
673                    _,
674                    ty::AnonConstKind::MCG
675                    | ty::AnonConstKind::NonTypeSystemAnon
676                    | ty::AnonConstKind::NonTypeSystemInline,
677                ))
678                | None => {
679                    // We are only dealing with "truly" generic/uninferred constants here:
680                    // - GCEConsts have been handled separately
681                    // - Repeat expr count back compat consts have also been handled separately
682                    // So we are free to simply defer evaluation here.
683                    //
684                    // FIXME: This assumes that `args` are normalized which is not necessarily true
685                    //
686                    // Const patterns are converted to type system constants before being
687                    // evaluated. However, we don't care about them here as pattern evaluation
688                    // logic does not go through type system normalization. If it did this would
689                    // be a backwards compatibility problem as we do not enforce "syntactic" non-
690                    // usage of generic parameters like we do here.
691                    if alias_const.args.has_non_region_param()
692                        || alias_const.args.has_non_region_infer()
693                        || alias_const.args.has_non_region_placeholders()
694                    {
695                        return Err(EvaluateConstErr::HasGenericsOrInfers);
696                    }
697
698                    // Since there is no generic parameter, we can just drop the environment
699                    // to prevent query cycle.
700                    let typing_env = ty::TypingEnv::fully_monomorphized();
701
702                    (alias_const.args, typing_env)
703                }
704            };
705
706            let alias_const = ty::AliasConst::new(tcx, alias_const.kind, args);
707            let erased_alias_const = tcx.erase_and_anonymize_regions(alias_const);
708
709            use rustc_middle::mir::interpret::ErrorHandled;
710            // FIXME: `def_span` will point at the definition of this const; ideally, we'd point at
711            // where it gets used as a const generic.
712            let span = alias_const.kind.def_span(tcx);
713            match tcx.const_eval_resolve_for_typeck(typing_env, erased_alias_const, span) {
714                Ok(Ok(val)) => {
715                    Ok(ty::Const::new_value(tcx, val, alias_const.type_of(tcx).skip_norm_wip()))
716                }
717                Ok(Err(_)) => {
718                    let e = tcx.dcx().delayed_bug(
719                        "Type system constant with non valtree'able type evaluated but no error emitted",
720                    );
721                    Err(EvaluateConstErr::InvalidConstParamTy(e))
722                }
723                Err(ErrorHandled::Reported(info, _)) => {
724                    Err(EvaluateConstErr::EvaluationFailure(info.into()))
725                }
726                Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
727            }
728        }
729    }
730}
731
732/// Replaces args that reference param or infer variables with suitable
733/// placeholders. This function is meant to remove these param and infer
734/// args when they're not actually needed to evaluate a constant.
735fn replace_param_and_infer_args_with_placeholder<'tcx>(
736    tcx: TyCtxt<'tcx>,
737    args: GenericArgsRef<'tcx>,
738) -> GenericArgsRef<'tcx> {
739    struct ReplaceParamAndInferWithPlaceholder<'tcx> {
740        tcx: TyCtxt<'tcx>,
741        idx: ty::BoundVar,
742    }
743
744    impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
745        fn cx(&self) -> TyCtxt<'tcx> {
746            self.tcx
747        }
748
749        fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
750            if let ty::Infer(_) = t.kind() {
751                let idx = self.idx;
752                self.idx += 1;
753                Ty::new_placeholder(
754                    self.tcx,
755                    ty::PlaceholderType::new(
756                        ty::UniverseIndex::ROOT,
757                        ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
758                    ),
759                )
760            } else {
761                t.super_fold_with(self)
762            }
763        }
764
765        fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
766            if let ty::ConstKind::Infer(_) = c.kind() {
767                let idx = self.idx;
768                self.idx += 1;
769                ty::Const::new_placeholder(
770                    self.tcx,
771                    ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)),
772                )
773            } else {
774                c.super_fold_with(self)
775            }
776        }
777    }
778
779    args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
780}
781
782/// Normalizes the clauses and checks whether they hold in an empty environment. If this
783/// returns true, then either normalize encountered an error or one of the predicates did not
784/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
785/// used during analysis.
786pub fn impossible_clauses<'tcx>(tcx: TyCtxt<'tcx>, clauses: Vec<ty::Clause<'tcx>>) -> bool {
787    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:787",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(787u32),
                        ::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);
788    let (infcx, param_env) = tcx
789        .infer_ctxt()
790        .with_next_trait_solver(true)
791        .enable_next_solver_overflow_fcw(false)
792        .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
793
794    let ocx = ObligationCtxt::new(&infcx);
795    let clauses =
796        ocx.normalize(&ObligationCause::dummy(), param_env, Unnormalized::new_wip(clauses));
797    for clause in clauses {
798        let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause);
799        ocx.register_obligation(obligation);
800    }
801
802    // Use `try_evaluate_obligations` to only return impossible for true errors,
803    // and not ambiguities or overflows. Since the new trait solver forces
804    // some currently undetected overlap between `dyn Trait: Trait` built-in
805    // vs user-written impls to AMBIGUOUS, this may return ambiguity even
806    // with no infer vars. There may also be ways to encounter ambiguity due
807    // to post-mono overflow.
808    let true_errors = ocx.try_evaluate_obligations();
809    if !true_errors.is_empty() {
810        return true;
811    }
812
813    false
814}
815
816fn instantiate_and_check_impossible_clauses<'tcx>(
817    tcx: TyCtxt<'tcx>,
818    key: (DefId, GenericArgsRef<'tcx>),
819) -> bool {
820    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:820",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(820u32),
                        ::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);
821
822    let mut clauses: Vec<_> = tcx
823        .clauses_of(key.0)
824        .instantiate(tcx, key.1)
825        .clauses
826        .into_iter()
827        .map(Unnormalized::skip_norm_wip)
828        .collect();
829
830    // Specifically check trait fulfillment to avoid an error when trying to resolve
831    // associated items.
832    if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
833        let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
834        clauses.push(trait_ref.upcast(tcx));
835    }
836
837    clauses.retain(|clause| !clause.has_param());
838    let result = impossible_clauses(tcx, clauses);
839
840    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:840",
                        "rustc_trait_selection::traits", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(840u32),
                        ::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);
841    result
842}
843
844/// Checks whether a trait's associated item is impossible to reference on a given impl.
845///
846/// This only considers predicates that reference the impl's generics, and not
847/// those that reference the method's generics.
848fn is_impossible_associated_item(
849    tcx: TyCtxt<'_>,
850    (impl_def_id, trait_item_def_id): (DefId, DefId),
851) -> bool {
852    struct ReferencesOnlyParentGenerics<'tcx> {
853        tcx: TyCtxt<'tcx>,
854        generics: &'tcx ty::Generics,
855        trait_item_def_id: DefId,
856    }
857    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
858        type Result = ControlFlow<()>;
859        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
860            // If this is a parameter from the trait item's own generics, then bail
861            if let ty::Param(param) = *t.kind()
862                && let param_def_id = self.generics.type_param(param, self.tcx).def_id
863                && self.tcx.parent(param_def_id) == self.trait_item_def_id
864            {
865                return ControlFlow::Break(());
866            }
867            t.super_visit_with(self)
868        }
869        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
870            if let ty::ReEarlyParam(param) = r.kind()
871                && let param_def_id = self.generics.region_param(param, self.tcx).def_id
872                && self.tcx.parent(param_def_id) == self.trait_item_def_id
873            {
874                return ControlFlow::Break(());
875            }
876            ControlFlow::Continue(())
877        }
878        fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
879            if let ty::ConstKind::Param(param) = ct.kind()
880                && let param_def_id = self.generics.const_param(param, self.tcx).def_id
881                && self.tcx.parent(param_def_id) == self.trait_item_def_id
882            {
883                return ControlFlow::Break(());
884            }
885            ct.super_visit_with(self)
886        }
887    }
888
889    let generics = tcx.generics_of(trait_item_def_id);
890    let gen_clauses = tcx.clauses_of(trait_item_def_id);
891
892    // Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
893    // since that method *may* have some substitutions where the predicates hold.
894    //
895    // This replicates the logic we use in coherence.
896    let infcx = tcx
897        .infer_ctxt()
898        .ignoring_regions()
899        .with_next_trait_solver(true)
900        .enable_next_solver_overflow_fcw(false)
901        .build(TypingMode::Coherence);
902    let param_env = ty::ParamEnv::empty();
903    let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
904
905    let impl_trait_ref =
906        tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args).skip_norm_wip();
907
908    let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
909    let predicates_for_trait = gen_clauses.clauses.iter().filter_map(|(clause, span)| {
910        clause.visit_with(&mut visitor).is_continue().then(|| {
911            Obligation::new(
912                tcx,
913                ObligationCause::dummy_with_span(*span),
914                param_env,
915                ty::EarlyBinder::bind(tcx, *clause)
916                    .instantiate(tcx, impl_trait_ref.args)
917                    .skip_norm_wip(),
918            )
919        })
920    });
921
922    let ocx = ObligationCtxt::new(&infcx);
923    ocx.register_obligations(predicates_for_trait);
924    !ocx.try_evaluate_obligations().is_empty()
925}
926
927pub fn provide(providers: &mut Providers) {
928    dyn_compatibility::provide(providers);
929    vtable::provide(providers);
930    *providers = Providers {
931        specialization_graph_of: specialize::specialization_graph_provider,
932        specializes: specialize::specializes,
933        specialization_enabled_in: specialize::specialization_enabled_in,
934        instantiate_and_check_impossible_clauses,
935        is_impossible_associated_item,
936        live_args_for_alias_from_outlives_bounds:
937            outlives_for_liveness::live_args_for_alias_from_outlives_bounds,
938        args_known_to_outlive_alias_params:
939            outlives_for_liveness::args_known_to_outlive_alias_params,
940        ..*providers
941    };
942}