Skip to main content

rustc_trait_selection/traits/
mod.rs

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