1//! Deeply normalize types using the old trait solver.
23use rustc_data_structures::stack::ensure_sufficient_stack;
4use rustc_errors::msg;
5use rustc_hir::def::DefKind;
6use rustc_infer::infer::at::At;
7use rustc_infer::infer::{InferCtxt, InferOk};
8use rustc_infer::traits::{
9FromSolverError, Normalized, Obligation, PredicateObligations, TraitEngine,
10};
11use rustc_macros::extension;
12use rustc_middle::span_bug;
13use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
14use rustc_middle::ty::{
15self, AliasTerm, Term, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
16TypeVisitableExt, TypingMode, Unnormalized,
17};
18use tracing::{debug, instrument};
1920use super::{BoundVarReplacer, PlaceholderReplacer, SelectionContext, project};
21use crate::error_reporting::InferCtxtErrorExt;
22use crate::error_reporting::traits::OverflowCause;
23use crate::solve::NextSolverError;
2425impl<'tcx> NormalizeExt<'tcx> for At<'_, 'tcx> {
#[doc = " Normalize a value using the `AssocTypeNormalizer`."]
#[doc = ""]
#[doc =
" This normalization should be used when the type contains inference variables or the"]
#[doc = " projection may be fallible."]
fn normalize<T: TypeFoldable<TyCtxt<'tcx>>>(&self,
value: Unnormalized<'tcx, T>) -> InferOk<'tcx, T> {
if self.infcx.next_trait_solver() {
let Normalized { value, obligations } =
crate::solve::normalize(*self, value);
InferOk { value, obligations }
} else {
let value = value.skip_normalization();
let mut selcx = SelectionContext::new(self.infcx);
let Normalized { value, obligations } =
normalize_with_depth(&mut selcx, self.param_env,
self.cause.clone(), 0, value);
InferOk { value, obligations }
}
}
#[doc =
" Deeply normalizes `value`, replacing all aliases which can by normalized in"]
#[doc =
" the current environment. In the new solver this errors in case normalization"]
#[doc = " fails or is ambiguous."]
#[doc = ""]
#[doc =
" In the old solver this simply uses `normalizes` and adds the nested obligations"]
#[doc =
" to the `fulfill_cx`. This is necessary as we otherwise end up recomputing the"]
#[doc =
" same goals in both a temporary and the shared context which negatively impacts"]
#[doc = " performance as these don\'t share caching."]
#[doc = ""]
#[doc =
" FIXME(-Znext-solver=no): For performance reasons, we currently reuse an existing"]
#[doc =
" fulfillment context in the old solver. Once we have removed the old solver, we"]
#[doc = " can remove the `fulfill_cx` parameter on this function."]
fn deeply_normalize<T,
E>(self, value: Unnormalized<'tcx, T>,
fulfill_cx: &mut dyn TraitEngine<'tcx, E>) -> Result<T, Vec<E>> where
T: TypeFoldable<TyCtxt<'tcx>>,
E: FromSolverError<'tcx, NextSolverError<'tcx>> {
if self.infcx.next_trait_solver() {
crate::solve::deeply_normalize(self, value)
} else {
if fulfill_cx.has_pending_obligations() {
let pending_obligations = fulfill_cx.pending_obligations();
::rustc_middle::util::bug::span_bug_fmt(pending_obligations[0].cause.span,
format_args!("deeply_normalize should not be called with pending obligations: {0:#?}",
pending_obligations));
}
let value =
self.normalize(value).into_value_registering_obligations(self.infcx,
&mut *fulfill_cx);
let errors =
fulfill_cx.evaluate_obligations_error_on_ambiguity(self.infcx);
let value = self.infcx.resolve_vars_if_possible(value);
if errors.is_empty() {
Ok(value)
} else {
let _ = fulfill_cx.collect_remaining_errors(self.infcx);
Err(errors)
}
}
}
}#[extension(pub trait NormalizeExt<'tcx>)]26impl<'tcx> At<'_, 'tcx> {
27/// Normalize a value using the `AssocTypeNormalizer`.
28 ///
29 /// This normalization should be used when the type contains inference variables or the
30 /// projection may be fallible.
31fn normalize<T: TypeFoldable<TyCtxt<'tcx>>>(
32&self,
33 value: Unnormalized<'tcx, T>,
34 ) -> InferOk<'tcx, T> {
35if self.infcx.next_trait_solver() {
36let Normalized { value, obligations } = crate::solve::normalize(*self, value);
37InferOk { value, obligations }
38 } else {
39let value = value.skip_normalization();
40let mut selcx = SelectionContext::new(self.infcx);
41let Normalized { value, obligations } =
42normalize_with_depth(&mut selcx, self.param_env, self.cause.clone(), 0, value);
43InferOk { value, obligations }
44 }
45 }
4647/// Deeply normalizes `value`, replacing all aliases which can by normalized in
48 /// the current environment. In the new solver this errors in case normalization
49 /// fails or is ambiguous.
50 ///
51 /// In the old solver this simply uses `normalizes` and adds the nested obligations
52 /// to the `fulfill_cx`. This is necessary as we otherwise end up recomputing the
53 /// same goals in both a temporary and the shared context which negatively impacts
54 /// performance as these don't share caching.
55 ///
56 /// FIXME(-Znext-solver=no): For performance reasons, we currently reuse an existing
57 /// fulfillment context in the old solver. Once we have removed the old solver, we
58 /// can remove the `fulfill_cx` parameter on this function.
59fn deeply_normalize<T, E>(
60self,
61 value: Unnormalized<'tcx, T>,
62 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
63 ) -> Result<T, Vec<E>>
64where
65T: TypeFoldable<TyCtxt<'tcx>>,
66 E: FromSolverError<'tcx, NextSolverError<'tcx>>,
67 {
68if self.infcx.next_trait_solver() {
69crate::solve::deeply_normalize(self, value)
70 } else {
71if fulfill_cx.has_pending_obligations() {
72let pending_obligations = fulfill_cx.pending_obligations();
73span_bug!(
74pending_obligations[0].cause.span,
75"deeply_normalize should not be called with pending obligations: \
76 {pending_obligations:#?}"
77);
78 }
79let value = self80 .normalize(value)
81 .into_value_registering_obligations(self.infcx, &mut *fulfill_cx);
82let errors = fulfill_cx.evaluate_obligations_error_on_ambiguity(self.infcx);
83let value = self.infcx.resolve_vars_if_possible(value);
84if errors.is_empty() {
85Ok(value)
86 } else {
87// Drop pending obligations, since deep normalization may happen
88 // in a loop and we don't want to trigger the assertion on the next
89 // iteration due to pending ambiguous obligations we've left over.
90let _ = fulfill_cx.collect_remaining_errors(self.infcx);
91Err(errors)
92 }
93 }
94 }
95}
9697/// As `normalize`, but with a custom depth.
98pub(crate) fn normalize_with_depth<'a, 'b, 'tcx, T>(
99 selcx: &'a mut SelectionContext<'b, 'tcx>,
100 param_env: ty::ParamEnv<'tcx>,
101 cause: ObligationCause<'tcx>,
102 depth: usize,
103 value: T,
104) -> Normalized<'tcx, T>
105where
106T: TypeFoldable<TyCtxt<'tcx>>,
107{
108let mut obligations = PredicateObligations::new();
109let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
110Normalized { value, obligations }
111}
112113#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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_with_depth_to",
"rustc_trait_selection::traits::normalize",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(113u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["depth", "value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&depth as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn 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: T = loop {};
return __tracing_attr_fake_return;
}
{
{
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/normalize.rs:125",
"rustc_trait_selection::traits::normalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(125u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["obligations.len"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&obligations.len()
as &dyn Value))])
});
} else { ; }
};
let mut normalizer =
AssocTypeNormalizer::new(selcx, param_env, cause, depth,
obligations);
let result =
ensure_sufficient_stack(||
AssocTypeNormalizer::fold(&mut normalizer, value));
{
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/normalize.rs:128",
"rustc_trait_selection::traits::normalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(128u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["result",
"obligations.len"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&normalizer.obligations.len()
as &dyn 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/normalize.rs:129",
"rustc_trait_selection::traits::normalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(129u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["normalizer.obligations"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&normalizer.obligations)
as &dyn Value))])
});
} else { ; }
};
result
}
}
}#[instrument(level = "info", skip(selcx, param_env, cause, obligations))]114pub(crate) fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
115 selcx: &'a mut SelectionContext<'b, 'tcx>,
116 param_env: ty::ParamEnv<'tcx>,
117 cause: ObligationCause<'tcx>,
118 depth: usize,
119 value: T,
120 obligations: &mut PredicateObligations<'tcx>,
121) -> T
122where
123T: TypeFoldable<TyCtxt<'tcx>>,
124{
125debug!(obligations.len = obligations.len());
126let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
127let result = ensure_sufficient_stack(|| AssocTypeNormalizer::fold(&mut normalizer, value));
128debug!(?result, obligations.len = normalizer.obligations.len());
129debug!(?normalizer.obligations,);
130 result
131}
132133pub(super) fn needs_normalization<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
134 infcx: &InferCtxt<'tcx>,
135 value: &T,
136) -> bool {
137let mut flags = ty::TypeFlags::HAS_ALIAS;
138139// Opaques are treated as rigid outside of `TypingMode::PostAnalysis`,
140 // so we can ignore those.
141match infcx.typing_mode() {
142// FIXME(#132279): We likely want to reveal opaques during post borrowck analysis
143TypingMode::Coherence144 | TypingMode::Analysis { .. }
145 | TypingMode::Borrowck { .. }
146 | TypingMode::PostBorrowckAnalysis { .. } => flags.remove(ty::TypeFlags::HAS_TY_OPAQUE),
147TypingMode::PostAnalysis => {}
148 }
149150value.has_type_flags(flags)
151}
152153struct AssocTypeNormalizer<'a, 'b, 'tcx> {
154 selcx: &'a mut SelectionContext<'b, 'tcx>,
155 param_env: ty::ParamEnv<'tcx>,
156 cause: ObligationCause<'tcx>,
157 obligations: &'a mut PredicateObligations<'tcx>,
158 depth: usize,
159 universes: Vec<Option<ty::UniverseIndex>>,
160}
161162impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
163fn new(
164 selcx: &'a mut SelectionContext<'b, 'tcx>,
165 param_env: ty::ParamEnv<'tcx>,
166 cause: ObligationCause<'tcx>,
167 depth: usize,
168 obligations: &'a mut PredicateObligations<'tcx>,
169 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
170if true {
if !!selcx.infcx.next_trait_solver() {
::core::panicking::panic("assertion failed: !selcx.infcx.next_trait_solver()")
};
};debug_assert!(!selcx.infcx.next_trait_solver());
171AssocTypeNormalizer { selcx, param_env, cause, obligations, depth, universes: ::alloc::vec::Vec::new()vec![] }
172 }
173174fn fold<T: TypeFoldable<TyCtxt<'tcx>>>(&mut self, value: T) -> T {
175let value = self.selcx.infcx.resolve_vars_if_possible(value);
176{
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/normalize.rs:176",
"rustc_trait_selection::traits::normalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(176u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["value"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&value) as
&dyn Value))])
});
} else { ; }
};debug!(?value);
177178if !!value.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("Normalizing {0:?} without wrapping in a `Binder`",
value));
}
};assert!(
179 !value.has_escaping_bound_vars(),
180"Normalizing {value:?} without wrapping in a `Binder`"
181);
182183if !needs_normalization(self.selcx.infcx, &value) { value } else { value.fold_with(self) }
184 }
185186// FIXME(mgca): While this supports constants, it is only used for types by default right now
187x;#[instrument(level = "debug", skip(self), ret)]188fn normalize_trait_projection(&mut self, proj: AliasTerm<'tcx>) -> Term<'tcx> {
189if !proj.has_escaping_bound_vars() {
190// When we don't have escaping bound vars we can normalize ambig aliases
191 // to inference variables (done in `normalize_projection_ty`). This would
192 // be wrong if there were escaping bound vars as even if we instantiated
193 // the bound vars with placeholders, we wouldn't be able to map them back
194 // after normalization succeeded.
195 //
196 // Also, as an optimization: when we don't have escaping bound vars, we don't
197 // need to replace them with placeholders (see branch below).
198let proj = proj.fold_with(self);
199 project::normalize_projection_term(
200self.selcx,
201self.param_env,
202 proj,
203self.cause.clone(),
204self.depth,
205self.obligations,
206 )
207 } else {
208// If there are escaping bound vars, we temporarily replace the
209 // bound vars with placeholders. Note though, that in the case
210 // that we still can't project for whatever reason (e.g. self
211 // type isn't known enough), we *can't* register an obligation
212 // and return an inference variable (since then that obligation
213 // would have bound vars and that's a can of worms). Instead,
214 // we just give up and fall back to pretending like we never tried!
215 //
216 // Note: this isn't necessarily the final approach here; we may
217 // want to figure out how to register obligations with escaping vars
218 // or handle this some other way.
219let infcx = self.selcx.infcx;
220let (proj, mapped_regions, mapped_types, mapped_consts) =
221 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, proj);
222let proj = proj.fold_with(self);
223let normalized_term = project::opt_normalize_projection_term(
224self.selcx,
225self.param_env,
226 proj,
227self.cause.clone(),
228self.depth,
229self.obligations,
230 )
231 .ok()
232 .flatten()
233 .unwrap_or_else(|| proj.to_term(infcx.tcx));
234235 PlaceholderReplacer::replace_placeholders(
236 infcx,
237 mapped_regions,
238 mapped_types,
239 mapped_consts,
240&self.universes,
241 normalized_term,
242 )
243 }
244 }
245246// FIXME(mgca): While this supports constants, it is only used for types by default right now
247x;#[instrument(level = "debug", skip(self), ret)]248fn normalize_inherent_projection(&mut self, inherent: AliasTerm<'tcx>) -> Term<'tcx> {
249if !inherent.has_escaping_bound_vars() {
250// When we don't have escaping bound vars we can normalize ambig aliases
251 // to inference variables (done in `normalize_projection_ty`). This would
252 // be wrong if there were escaping bound vars as even if we instantiated
253 // the bound vars with placeholders, we wouldn't be able to map them back
254 // after normalization succeeded.
255 //
256 // Also, as an optimization: when we don't have escaping bound vars, we don't
257 // need to replace them with placeholders (see branch below).
258259let inherent = inherent.fold_with(self);
260 project::normalize_inherent_projection(
261self.selcx,
262self.param_env,
263 inherent,
264self.cause.clone(),
265self.depth,
266self.obligations,
267 )
268 } else {
269let infcx = self.selcx.infcx;
270let (inherent, mapped_regions, mapped_types, mapped_consts) =
271 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, inherent);
272let inherent = inherent.fold_with(self);
273let inherent = project::normalize_inherent_projection(
274self.selcx,
275self.param_env,
276 inherent,
277self.cause.clone(),
278self.depth,
279self.obligations,
280 );
281282 PlaceholderReplacer::replace_placeholders(
283 infcx,
284 mapped_regions,
285 mapped_types,
286 mapped_consts,
287&self.universes,
288 inherent,
289 )
290 }
291 }
292293// FIXME(mgca): While this supports constants, it is only used for types by default right now
294x;#[instrument(level = "debug", skip(self), ret)]295fn normalize_free_alias(&mut self, free: AliasTerm<'tcx>) -> Term<'tcx> {
296let recursion_limit = self.cx().recursion_limit();
297if !recursion_limit.value_within_limit(self.depth) {
298self.selcx.infcx.err_ctxt().report_overflow_error(
299 OverflowCause::DeeplyNormalize(free.into()),
300self.cause.span,
301false,
302 |diag| {
303 diag.note(msg!("in case this is a recursive type alias, consider using a struct, enum, or union instead"));
304 },
305 );
306 }
307308// We don't replace bound vars in the generic arguments of the free alias with
309 // placeholders. This doesn't cause any issues as instantiating parameters with
310 // bound variables is special-cased to rewrite the debruijn index to be higher
311 // whenever we fold through a binder.
312 //
313 // However, we do replace any escaping bound vars in the resulting goals with
314 // placeholders as the trait solver does not expect to encounter escaping bound
315 // vars in obligations.
316 //
317 // FIXME(lazy_type_alias): Check how much this actually matters for perf before
318 // stabilization. This is a bit weird and generally not how we handle binders in
319 // the compiler so ideally we'd do the same boundvar->placeholder->boundvar dance
320 // that other kinds of normalization do.
321let infcx = self.selcx.infcx;
322self.obligations.extend(
323 infcx
324 .tcx
325 .predicates_of(free.def_id())
326 .instantiate_own(infcx.tcx, free.args)
327 .map(|(pred, span)| (pred.skip_norm_wip(), span))
328 .map(|(mut predicate, span)| {
329if free.has_escaping_bound_vars() {
330 (predicate, ..) = BoundVarReplacer::replace_bound_vars(
331 infcx,
332&mut self.universes,
333 predicate,
334 );
335 }
336let mut cause = self.cause.clone();
337 cause
338 .map_code(|code| ObligationCauseCode::TypeAlias(code, span, free.def_id()));
339 Obligation::new(infcx.tcx, cause, self.param_env, predicate)
340 }),
341 );
342self.depth += 1;
343let res = if free.kind(infcx.tcx).is_type() {
344 infcx
345 .tcx
346 .type_of(free.def_id())
347 .instantiate(infcx.tcx, free.args)
348 .skip_norm_wip()
349 .fold_with(self)
350 .into()
351 } else {
352 infcx
353 .tcx
354 .const_of_item(free.def_id())
355 .instantiate(infcx.tcx, free.args)
356 .skip_norm_wip()
357 .fold_with(self)
358 .into()
359 };
360self.depth -= 1;
361 res
362 }
363}
364365impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx> {
366fn cx(&self) -> TyCtxt<'tcx> {
367self.selcx.tcx()
368 }
369370fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
371&mut self,
372 t: ty::Binder<'tcx, T>,
373 ) -> ty::Binder<'tcx, T> {
374self.universes.push(None);
375let t = t.super_fold_with(self);
376self.universes.pop();
377t378 }
379380fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
381if !needs_normalization(self.selcx.infcx, &ty) {
382return ty;
383 }
384385let ty::Alias(data) = *ty.kind() else { return ty.super_fold_with(self) };
386387// We try to be a little clever here as a performance optimization in
388 // cases where there are nested projections under binders.
389 // For example:
390 // ```
391 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
392 // ```
393 // We normalize the args on the projection before the projecting, but
394 // if we're naive, we'll
395 // replace bound vars on inner, project inner, replace placeholders on inner,
396 // replace bound vars on outer, project outer, replace placeholders on outer
397 //
398 // However, if we're a bit more clever, we can replace the bound vars
399 // on the entire type before normalizing nested projections, meaning we
400 // replace bound vars on outer, project inner,
401 // project outer, replace placeholders on outer
402 //
403 // This is possible because the inner `'a` will already be a placeholder
404 // when we need to normalize the inner projection
405 //
406 // On the other hand, this does add a bit of complexity, since we only
407 // replace bound vars if the current type is a `Projection` and we need
408 // to make sure we don't forget to fold the args regardless.
409410match data.kind {
411 ty::Opaque { def_id } => {
412// Only normalize `impl Trait` outside of type inference, usually in codegen.
413match self.selcx.infcx.typing_mode() {
414// FIXME(#132279): We likely want to reveal opaques during post borrowck analysis
415TypingMode::Coherence416 | TypingMode::Analysis { .. }
417 | TypingMode::Borrowck { .. }
418 | TypingMode::PostBorrowckAnalysis { .. } => ty.super_fold_with(self),
419TypingMode::PostAnalysis => {
420let recursion_limit = self.cx().recursion_limit();
421if !recursion_limit.value_within_limit(self.depth) {
422self.selcx.infcx.err_ctxt().report_overflow_error(
423 OverflowCause::DeeplyNormalize(data.into()),
424self.cause.span,
425true,
426 |_| {},
427 );
428 }
429430let args = data.args.fold_with(self);
431let generic_ty = self.cx().type_of(def_id);
432let concrete_ty = generic_ty.instantiate(self.cx(), args).skip_norm_wip();
433self.depth += 1;
434let folded_ty = self.fold_ty(concrete_ty);
435self.depth -= 1;
436folded_ty437 }
438 }
439 }
440441 ty::Projection { .. } => self.normalize_trait_projection(data.into()).expect_type(),
442 ty::Inherent { .. } => self.normalize_inherent_projection(data.into()).expect_type(),
443 ty::Free { .. } => self.normalize_free_alias(data.into()).expect_type(),
444 }
445 }
446447#[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("fold_const",
"rustc_trait_selection::traits::normalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/normalize.rs"),
::tracing_core::__macro_support::Option::Some(447u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::normalize"),
::tracing_core::field::FieldSet::new(&["ct"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
as &dyn 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::Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.selcx.tcx();
if tcx.features().generic_const_exprs() &&
!#[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Unevaluated(uv) if tcx.is_type_const(uv.def)
=> true,
_ => false,
} || !needs_normalization(self.selcx.infcx, &ct) {
return ct;
}
let uv =
match ct.kind() {
ty::ConstKind::Unevaluated(uv) => uv,
_ => return ct.super_fold_with(self),
};
let ct =
match tcx.def_kind(uv.def) {
DefKind::AssocConst { .. } =>
match tcx.def_kind(tcx.parent(uv.def)) {
DefKind::Trait =>
self.normalize_trait_projection(ty::AliasTerm::from_unevaluated_const(tcx,
uv)).expect_const(),
DefKind::Impl { of_trait: false } =>
self.normalize_inherent_projection(ty::AliasTerm::from_unevaluated_const(tcx,
uv)).expect_const(),
kind => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unexpected `DefKind` for const alias\' resolution\'s parent def: {0:?}",
kind)));
}
},
DefKind::Const { .. } =>
self.normalize_free_alias(ty::AliasTerm::from_unevaluated_const(tcx,
uv)).expect_const(),
DefKind::AnonConst => {
let ct = ct.super_fold_with(self);
super::with_replaced_escaping_bound_vars(self.selcx.infcx,
&mut self.universes, ct,
|ct|
super::evaluate_const(self.selcx.infcx, ct, self.param_env))
}
kind => {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unexpected `DefKind` for const alias to resolve to: {0:?}",
kind)));
}
}
};
ct.super_fold_with(self)
}
}
}#[instrument(skip(self), level = "debug")]448fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
449let tcx = self.selcx.tcx();
450451if tcx.features().generic_const_exprs()
452// Normalize type_const items even with feature `generic_const_exprs`.
453&& !matches!(ct.kind(), ty::ConstKind::Unevaluated(uv) if tcx.is_type_const(uv.def))
454 || !needs_normalization(self.selcx.infcx, &ct)
455 {
456return ct;
457 }
458459let uv = match ct.kind() {
460 ty::ConstKind::Unevaluated(uv) => uv,
461_ => return ct.super_fold_with(self),
462 };
463464// Note that the AssocConst and Const cases are unreachable on stable,
465 // unless a `min_generic_const_args` feature gate error has already
466 // been emitted earlier in compilation.
467 //
468 // That's because we can only end up with an Unevaluated ty::Const for a const item
469 // if it was marked with `type const`. Using this attribute without the mgca
470 // feature gate causes a parse error.
471let ct = match tcx.def_kind(uv.def) {
472 DefKind::AssocConst { .. } => match tcx.def_kind(tcx.parent(uv.def)) {
473 DefKind::Trait => self
474.normalize_trait_projection(ty::AliasTerm::from_unevaluated_const(tcx, uv))
475 .expect_const(),
476 DefKind::Impl { of_trait: false } => self
477.normalize_inherent_projection(ty::AliasTerm::from_unevaluated_const(tcx, uv))
478 .expect_const(),
479 kind => unreachable!(
480"unexpected `DefKind` for const alias' resolution's parent def: {:?}",
481 kind
482 ),
483 },
484 DefKind::Const { .. } => self
485.normalize_free_alias(ty::AliasTerm::from_unevaluated_const(tcx, uv))
486 .expect_const(),
487 DefKind::AnonConst => {
488let ct = ct.super_fold_with(self);
489super::with_replaced_escaping_bound_vars(
490self.selcx.infcx,
491&mut self.universes,
492 ct,
493 |ct| super::evaluate_const(self.selcx.infcx, ct, self.param_env),
494 )
495 }
496 kind => {
497unreachable!("unexpected `DefKind` for const alias to resolve to: {:?}", kind)
498 }
499 };
500501// We re-fold the normalized const as the `ty` field on `ConstKind::Value` may be
502 // unnormalized after const evaluation returns.
503ct.super_fold_with(self)
504 }
505506#[inline]
507fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
508if p.allow_normalization() && needs_normalization(self.selcx.infcx, &p) {
509p.super_fold_with(self)
510 } else {
511p512 }
513 }
514}