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