Skip to main content

rustc_trait_selection/traits/query/
normalize.rs

1//! Code for the 'normalization' query. This consists of a wrapper
2//! which folds deeply, invoking the underlying
3//! `normalize_canonicalized_projection` query when it encounters projections.
4
5use rustc_data_structures::sso::SsoHashMap;
6use rustc_infer::traits::PredicateObligations;
7use rustc_macros::extension;
8pub use rustc_middle::traits::query::NormalizationResult;
9use rustc_middle::ty::{
10    self, FallibleTypeFolder, Flags, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable,
11    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
12};
13use rustc_span::DUMMY_SP;
14use tracing::{debug, info, instrument};
15
16use super::NoSolution;
17use crate::error_reporting::InferCtxtErrorExt;
18use crate::error_reporting::traits::OverflowCause;
19use crate::infer::at::At;
20use crate::infer::canonical::OriginalQueryValues;
21use crate::infer::{InferCtxt, InferOk};
22use crate::traits::normalize::needs_normalization;
23use crate::traits::{
24    BoundVarReplacer, Normalized, ObligationCause, PlaceholderReplacer, ScrubbedTraitError,
25};
26
27impl<'a, 'tcx> QueryNormalizeExt<'tcx> for At<'a, 'tcx> {
    #[doc = " Normalize `value` in the context of the inference context,"]
    #[doc = " yielding a resulting type, or an error if `value` cannot be"]
    #[doc =
    " normalized. If you don\'t care about regions, you should prefer"]
    #[doc = " `normalize_erasing_regions`, which is more efficient."]
    #[doc = ""]
    #[doc = " If the normalization succeeds, returns back the normalized"]
    #[doc = " value along with various outlives relations (in the form of"]
    #[doc = " obligations that must be discharged)."]
    #[doc = ""]
    #[doc =
    " This normalization should *only* be used when the projection is well-formed and"]
    #[doc =
    " does not have possible ambiguity (contains inference variables)."]
    #[doc = ""]
    #[doc =
    " After codegen, when lifetimes do not matter, it is preferable to instead"]
    #[doc =
    " use [`TyCtxt::normalize_erasing_regions`], which wraps this procedure."]
    #[doc = ""]
    #[doc =
    " N.B. Once the new solver is stabilized this method of normalization will"]
    #[doc =
    " likely be removed as trait solver operations are already cached by the query"]
    #[doc = " system making this redundant."]
    fn query_normalize<T>(self, value: T)
        -> Result<Normalized<'tcx, T>, NoSolution> where
        T: TypeFoldable<TyCtxt<'tcx>> {
        {
            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/query/normalize.rs:51",
                                "rustc_trait_selection::traits::query::normalize",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                                ::tracing_core::__macro_support::Option::Some(51u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                                ::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::<{0}>(value={1:?}, param_env={2:?}, cause={3:?})",
                                                            std::any::type_name::<T>(), value, self.param_env,
                                                            self.cause) as &dyn ::tracing::field::Value))])
                    });
            } else { ; }
        };
        let universes =
            if value.has_escaping_bound_vars() {
                let mut max_visitor =
                    MaxEscapingBoundVarVisitor {
                        outer_index: ty::INNERMOST,
                        escaping: 0,
                    };
                value.visit_with(&mut max_visitor);
                ::alloc::vec::from_elem(None, max_visitor.escaping)
            } else { ::alloc::vec::Vec::new() };
        if self.infcx.next_trait_solver() {
            match crate::solve::deeply_normalize_with_skipped_universes::<_,
                        ScrubbedTraitError<'tcx>>(self,
                    Unnormalized::new_wip(value), universes) {
                Ok(value) => {
                    return Ok(Normalized {
                                value,
                                obligations: PredicateObligations::new(),
                            });
                }
                Err(_errors) => { return Err(NoSolution); }
            }
        }
        if !needs_normalization(self.infcx, &value) {
            return Ok(Normalized {
                        value,
                        obligations: PredicateObligations::new(),
                    });
        }
        let mut normalizer =
            QueryNormalizer {
                infcx: self.infcx,
                cause: self.cause,
                param_env: self.param_env,
                obligations: PredicateObligations::new(),
                cache: SsoHashMap::new(),
                anon_depth: 0,
                universes,
            };
        let result = value.try_fold_with(&mut normalizer);
        {
            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/query/normalize.rs:108",
                                "rustc_trait_selection::traits::query::normalize",
                                ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                                ::tracing_core::__macro_support::Option::Some(108u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                                ::tracing_core::field::FieldSet::new(&["message"],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::EVENT)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let enabled =
                ::tracing::Level::INFO <=
                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                        ::tracing::Level::INFO <=
                            ::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::<{0}>: result={1:?} with {2} obligations",
                                                            std::any::type_name::<T>(), result,
                                                            normalizer.obligations.len()) as
                                                    &dyn ::tracing::field::Value))])
                    });
            } else { ; }
        };
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/query/normalize.rs:114",
                                "rustc_trait_selection::traits::query::normalize",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                                ::tracing_core::__macro_support::Option::Some(114u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                                ::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::<{0}>: obligations={1:?}",
                                                            std::any::type_name::<T>(), normalizer.obligations) as
                                                    &dyn ::tracing::field::Value))])
                    });
            } else { ; }
        };
        result.map(|value|
                Normalized { value, obligations: normalizer.obligations })
    }
}#[extension(pub trait QueryNormalizeExt<'tcx>)]
28impl<'a, 'tcx> At<'a, 'tcx> {
29    /// Normalize `value` in the context of the inference context,
30    /// yielding a resulting type, or an error if `value` cannot be
31    /// normalized. If you don't care about regions, you should prefer
32    /// `normalize_erasing_regions`, which is more efficient.
33    ///
34    /// If the normalization succeeds, returns back the normalized
35    /// value along with various outlives relations (in the form of
36    /// obligations that must be discharged).
37    ///
38    /// This normalization should *only* be used when the projection is well-formed and
39    /// does not have possible ambiguity (contains inference variables).
40    ///
41    /// After codegen, when lifetimes do not matter, it is preferable to instead
42    /// use [`TyCtxt::normalize_erasing_regions`], which wraps this procedure.
43    ///
44    /// N.B. Once the new solver is stabilized this method of normalization will
45    /// likely be removed as trait solver operations are already cached by the query
46    /// system making this redundant.
47    fn query_normalize<T>(self, value: T) -> Result<Normalized<'tcx, T>, NoSolution>
48    where
49        T: TypeFoldable<TyCtxt<'tcx>>,
50    {
51        debug!(
52            "normalize::<{}>(value={:?}, param_env={:?}, cause={:?})",
53            std::any::type_name::<T>(),
54            value,
55            self.param_env,
56            self.cause,
57        );
58
59        // This is actually a consequence by the way `normalize_erasing_regions` works currently.
60        // Because it needs to call the `normalize_generic_arg_after_erasing_regions`, it folds
61        // through tys and consts in a `TypeFoldable`. Importantly, it skips binders, leaving us
62        // with trying to normalize with escaping bound vars.
63        //
64        // Here, we just add the universes that we *would* have created had we passed through the binders.
65        //
66        // We *could* replace escaping bound vars eagerly here, but it doesn't seem really necessary.
67        // The rest of the code is already set up to be lazy about replacing bound vars,
68        // and only when we actually have to normalize.
69        let universes = if value.has_escaping_bound_vars() {
70            let mut max_visitor =
71                MaxEscapingBoundVarVisitor { outer_index: ty::INNERMOST, escaping: 0 };
72            value.visit_with(&mut max_visitor);
73            vec![None; max_visitor.escaping]
74        } else {
75            vec![]
76        };
77
78        if self.infcx.next_trait_solver() {
79            match crate::solve::deeply_normalize_with_skipped_universes::<_, ScrubbedTraitError<'tcx>>(
80                self,
81                Unnormalized::new_wip(value),
82                universes,
83            ) {
84                Ok(value) => {
85                    return Ok(Normalized { value, obligations: PredicateObligations::new() });
86                }
87                Err(_errors) => {
88                    return Err(NoSolution);
89                }
90            }
91        }
92
93        if !needs_normalization(self.infcx, &value) {
94            return Ok(Normalized { value, obligations: PredicateObligations::new() });
95        }
96
97        let mut normalizer = QueryNormalizer {
98            infcx: self.infcx,
99            cause: self.cause,
100            param_env: self.param_env,
101            obligations: PredicateObligations::new(),
102            cache: SsoHashMap::new(),
103            anon_depth: 0,
104            universes,
105        };
106
107        let result = value.try_fold_with(&mut normalizer);
108        info!(
109            "normalize::<{}>: result={:?} with {} obligations",
110            std::any::type_name::<T>(),
111            result,
112            normalizer.obligations.len(),
113        );
114        debug!(
115            "normalize::<{}>: obligations={:?}",
116            std::any::type_name::<T>(),
117            normalizer.obligations,
118        );
119        result.map(|value| Normalized { value, obligations: normalizer.obligations })
120    }
121}
122
123// Visitor to find the maximum escaping bound var
124struct MaxEscapingBoundVarVisitor {
125    // The index which would count as escaping
126    outer_index: ty::DebruijnIndex,
127    escaping: usize,
128}
129
130impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MaxEscapingBoundVarVisitor {
131    fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &ty::Binder<'tcx, T>) {
132        self.outer_index.shift_in(1);
133        t.super_visit_with(self);
134        self.outer_index.shift_out(1);
135    }
136
137    #[inline]
138    fn visit_ty(&mut self, t: Ty<'tcx>) {
139        if t.outer_exclusive_binder() > self.outer_index {
140            self.escaping = self
141                .escaping
142                .max(t.outer_exclusive_binder().as_usize() - self.outer_index.as_usize());
143        }
144    }
145
146    #[inline]
147    fn visit_region(&mut self, r: ty::Region<'tcx>) {
148        match r.kind() {
149            ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), _)
150                if debruijn > self.outer_index =>
151            {
152                self.escaping =
153                    self.escaping.max(debruijn.as_usize() - self.outer_index.as_usize());
154            }
155            _ => {}
156        }
157    }
158
159    fn visit_const(&mut self, ct: ty::Const<'tcx>) {
160        if ct.outer_exclusive_binder() > self.outer_index {
161            self.escaping = self
162                .escaping
163                .max(ct.outer_exclusive_binder().as_usize() - self.outer_index.as_usize());
164        }
165    }
166}
167
168struct QueryNormalizer<'a, 'tcx> {
169    infcx: &'a InferCtxt<'tcx>,
170    cause: &'a ObligationCause<'tcx>,
171    param_env: ty::ParamEnv<'tcx>,
172    obligations: PredicateObligations<'tcx>,
173    cache: SsoHashMap<Ty<'tcx>, Ty<'tcx>>,
174    anon_depth: usize,
175    universes: Vec<Option<ty::UniverseIndex>>,
176}
177
178impl<'a, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'a, 'tcx> {
179    type Error = NoSolution;
180
181    fn cx(&self) -> TyCtxt<'tcx> {
182        self.infcx.tcx
183    }
184
185    fn try_fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
186        &mut self,
187        t: ty::Binder<'tcx, T>,
188    ) -> Result<ty::Binder<'tcx, T>, Self::Error> {
189        self.universes.push(None);
190        let t = t.try_super_fold_with(self);
191        self.universes.pop();
192        t
193    }
194
195    #[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("try_fold_ty",
                                    "rustc_trait_selection::traits::query::normalize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                                    ::tracing_core::__macro_support::Option::Some(195u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        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(&ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Ty<'tcx>, Self::Error> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !needs_normalization(self.infcx, &ty) { return Ok(ty); }
            if let Some(ty) = self.cache.get(&ty) { return Ok(*ty); }
            let &ty::Alias(_, data) =
                ty.kind() else {
                    let res = ty.try_super_fold_with(self)?;
                    self.cache.insert(ty, res);
                    return Ok(res);
                };
            let res =
                match data.kind {
                    ty::Opaque { def_id } => {
                        match self.infcx.typing_mode_raw().assert_not_erased() {
                            TypingMode::Coherence | TypingMode::Typeck { .. } |
                                TypingMode::PostTypeckUntilBorrowck { .. } |
                                TypingMode::PostBorrowck { .. } =>
                                ty.try_super_fold_with(self)?,
                            TypingMode::Reflection | TypingMode::PostAnalysis |
                                TypingMode::Codegen => {
                                let args = data.args.try_fold_with(self)?;
                                let recursion_limit = self.cx().recursion_limit();
                                if !recursion_limit.value_within_limit(self.anon_depth) {
                                    let guar =
                                        self.infcx.err_ctxt().build_overflow_error(OverflowCause::DeeplyNormalize(data.into()),
                                                self.cause.span, true).delay_as_bug();
                                    return Ok(Ty::new_error(self.cx(), guar));
                                }
                                let generic_ty = self.cx().type_of(def_id);
                                let mut concrete_ty =
                                    generic_ty.instantiate(self.cx(), args).skip_norm_wip();
                                self.anon_depth += 1;
                                if concrete_ty == ty {
                                    concrete_ty =
                                        Ty::new_error_with_message(self.cx(), DUMMY_SP,
                                            "recursive opaque type");
                                }
                                let folded_ty = self.try_fold_ty(concrete_ty);
                                self.anon_depth -= 1;
                                folded_ty?
                            }
                        }
                    }
                    kind @
                        (ty::Projection { .. } | ty::Inherent { .. } | ty::Free { ..
                        }) =>
                        self.try_fold_free_or_assoc(ty::AliasTerm::new(self.cx(),
                                        kind.into(), data.args))?.expect_type(),
                };
            self.cache.insert(ty, res);
            Ok(res)
        }
    }
}#[instrument(level = "debug", skip(self))]
196    fn try_fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
197        if !needs_normalization(self.infcx, &ty) {
198            return Ok(ty);
199        }
200
201        if let Some(ty) = self.cache.get(&ty) {
202            return Ok(*ty);
203        }
204
205        let &ty::Alias(_, data) = ty.kind() else {
206            let res = ty.try_super_fold_with(self)?;
207            self.cache.insert(ty, res);
208            return Ok(res);
209        };
210
211        // See note in `rustc_trait_selection::traits::project` about why we
212        // wait to fold the args.
213        let res = match data.kind {
214            ty::Opaque { def_id } => {
215                // Only normalize `impl Trait` outside of type inference, usually in codegen.
216                match self.infcx.typing_mode_raw().assert_not_erased() {
217                    TypingMode::Coherence
218                    | TypingMode::Typeck { .. }
219                    | TypingMode::PostTypeckUntilBorrowck { .. }
220                    | TypingMode::PostBorrowck { .. } => ty.try_super_fold_with(self)?,
221
222                    TypingMode::Reflection | TypingMode::PostAnalysis | TypingMode::Codegen => {
223                        let args = data.args.try_fold_with(self)?;
224                        let recursion_limit = self.cx().recursion_limit();
225
226                        if !recursion_limit.value_within_limit(self.anon_depth) {
227                            let guar = self
228                                .infcx
229                                .err_ctxt()
230                                .build_overflow_error(
231                                    OverflowCause::DeeplyNormalize(data.into()),
232                                    self.cause.span,
233                                    true,
234                                )
235                                .delay_as_bug();
236                            return Ok(Ty::new_error(self.cx(), guar));
237                        }
238
239                        let generic_ty = self.cx().type_of(def_id);
240                        let mut concrete_ty =
241                            generic_ty.instantiate(self.cx(), args).skip_norm_wip();
242                        self.anon_depth += 1;
243                        if concrete_ty == ty {
244                            concrete_ty = Ty::new_error_with_message(
245                                self.cx(),
246                                DUMMY_SP,
247                                "recursive opaque type",
248                            );
249                        }
250                        let folded_ty = self.try_fold_ty(concrete_ty);
251                        self.anon_depth -= 1;
252                        folded_ty?
253                    }
254                }
255            }
256
257            kind @ (ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. }) => self
258                .try_fold_free_or_assoc(ty::AliasTerm::new(self.cx(), kind.into(), data.args))?
259                .expect_type(),
260        };
261
262        self.cache.insert(ty, res);
263        Ok(res)
264    }
265
266    fn try_fold_const(
267        &mut self,
268        constant: ty::Const<'tcx>,
269    ) -> Result<ty::Const<'tcx>, Self::Error> {
270        if !needs_normalization(self.infcx, &constant) {
271            return Ok(constant);
272        }
273
274        let alias_const = match constant.kind() {
275            ty::ConstKind::Alias(_, alias_const) => alias_const,
276            _ => return constant.try_super_fold_with(self),
277        };
278
279        let constant = match alias_const.kind {
280            ty::AliasConstKind::Anon { .. } => crate::traits::with_replaced_escaping_bound_vars(
281                self.infcx,
282                &mut self.universes,
283                constant,
284                |constant| crate::traits::evaluate_const(&self.infcx, constant, self.param_env),
285            ),
286            _ => self.try_fold_free_or_assoc(alias_const.into())?.expect_const(),
287        };
288        {
    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/query/normalize.rs:288",
                        "rustc_trait_selection::traits::query::normalize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                        ::tracing_core::__macro_support::Option::Some(288u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("constant")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("constant");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.param_env")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.param_env");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constant)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.param_env)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?constant, ?self.param_env);
289        constant.try_super_fold_with(self)
290    }
291
292    #[inline]
293    fn try_fold_predicate(
294        &mut self,
295        p: ty::Predicate<'tcx>,
296    ) -> Result<ty::Predicate<'tcx>, Self::Error> {
297        if p.allow_normalization() && needs_normalization(self.infcx, &p) {
298            p.try_super_fold_with(self)
299        } else {
300            Ok(p)
301        }
302    }
303}
304
305impl<'a, 'tcx> QueryNormalizer<'a, 'tcx> {
306    fn try_fold_free_or_assoc(
307        &mut self,
308        term: ty::AliasTerm<'tcx>,
309    ) -> Result<ty::Term<'tcx>, NoSolution> {
310        let infcx = self.infcx;
311        let tcx = infcx.tcx;
312        // Just an optimization: When we don't have escaping bound vars,
313        // we don't need to replace them with placeholders.
314        let (term, maps) = if term.has_escaping_bound_vars() {
315            let (term, mapped_regions, mapped_types, mapped_consts) =
316                BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, term);
317            (term, Some((mapped_regions, mapped_types, mapped_consts)))
318        } else {
319            (term, None)
320        };
321        let term = term.try_fold_with(self)?;
322
323        let mut orig_values = OriginalQueryValues::default();
324        let c_term = infcx.canonicalize_query(self.param_env.and(term), &mut orig_values);
325        {
    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/query/normalize.rs:325",
                        "rustc_trait_selection::traits::query::normalize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                        ::tracing_core::__macro_support::Option::Some(325u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                        ::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!("QueryNormalizer: c_term = {0:#?}",
                                                    c_term) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("QueryNormalizer: c_term = {:#?}", c_term);
326        {
    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/query/normalize.rs:326",
                        "rustc_trait_selection::traits::query::normalize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                        ::tracing_core::__macro_support::Option::Some(326u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                        ::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!("QueryNormalizer: orig_values = {0:#?}",
                                                    orig_values) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("QueryNormalizer: orig_values = {:#?}", orig_values);
327        let result = match term.kind {
328            ty::AliasTermKind::ProjectionTy { .. } | ty::AliasTermKind::ProjectionConst { .. } => {
329                tcx.normalize_canonicalized_projection(c_term)
330            }
331            ty::AliasTermKind::FreeTy { .. } | ty::AliasTermKind::FreeConst { .. } => {
332                tcx.normalize_canonicalized_free_alias(c_term)
333            }
334            ty::AliasTermKind::InherentTy { .. } | ty::AliasTermKind::InherentConst { .. } => {
335                tcx.normalize_canonicalized_inherent_projection(c_term)
336            }
337            kind @ (ty::AliasTermKind::OpaqueTy { .. } | ty::AliasTermKind::AnonConst { .. }) => {
338                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("did not expect {0:?} due to match arm above",
                kind)));
}unreachable!("did not expect {kind:?} due to match arm above")
339            }
340        }?;
341        // We don't expect ambiguity.
342        if !result.value.is_proven() {
343            // Rustdoc normalizes possibly not well-formed types, so only
344            // treat this as a bug if we're not in rustdoc.
345            if !tcx.sess.opts.actually_rustdoc {
346                tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected ambiguity: {0:?} {1:?}",
                c_term, result))
    })format!("unexpected ambiguity: {c_term:?} {result:?}"));
347            }
348            return Err(NoSolution);
349        }
350        let InferOk { value: result, obligations } = infcx
351            .instantiate_query_response_and_region_obligations(
352                self.cause,
353                self.param_env,
354                &orig_values,
355                result,
356            )?;
357        {
    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/query/normalize.rs:357",
                        "rustc_trait_selection::traits::query::normalize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                        ::tracing_core::__macro_support::Option::Some(357u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                        ::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!("QueryNormalizer: result = {0:#?}",
                                                    result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("QueryNormalizer: result = {:#?}", result);
358        {
    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/query/normalize.rs:358",
                        "rustc_trait_selection::traits::query::normalize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/query/normalize.rs"),
                        ::tracing_core::__macro_support::Option::Some(358u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::normalize"),
                        ::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!("QueryNormalizer: obligations = {0:#?}",
                                                    obligations) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("QueryNormalizer: obligations = {:#?}", obligations);
359        self.obligations.extend(obligations);
360        let res = if let Some((mapped_regions, mapped_types, mapped_consts)) = maps {
361            PlaceholderReplacer::replace_placeholders(
362                infcx,
363                mapped_regions,
364                mapped_types,
365                mapped_consts,
366                &self.universes,
367                result.normalized_term,
368            )
369        } else {
370            result.normalized_term
371        };
372        // `tcx.normalize_canonicalized_projection` may normalize to a type that
373        // still has alias consts, so keep normalizing here if that's the case.
374        // Similarly, `tcx.normalize_canonicalized_free_alias` will only unwrap one layer
375        // of type/const and we need to continue folding it to reveal the TAIT behind it
376        // or further normalize nested alias consts.
377        if res != term.to_term(tcx, ty::IsRigid::No)
378            && (res.has_type_flags(ty::TypeFlags::HAS_CONST_ALIAS)
379                || #[allow(non_exhaustive_omitted_patterns)] match term.kind {
    ty::AliasTermKind::FreeTy { .. } | ty::AliasTermKind::FreeConst { .. } =>
        true,
    _ => false,
}matches!(
380                    term.kind,
381                    ty::AliasTermKind::FreeTy { .. } | ty::AliasTermKind::FreeConst { .. }
382                ))
383        {
384            res.try_fold_with(self)
385        } else {
386            Ok(res)
387        }
388    }
389}