1//! Deeply normalize types using the old trait solver.
23use rustc_data_structures::stack::ensure_sufficient_stack;
4use rustc_hir::def::DefKind;
5use rustc_infer::infer::at::At;
6use rustc_infer::infer::{InferCtxt, InferOk};
7use rustc_infer::traits::{
8FromSolverError, Normalized, Obligation, PredicateObligations, TraitEngine,
9};
10use rustc_macros::extension;
11use rustc_middle::span_bug;
12use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
13use rustc_middle::ty::{
14self, AliasTerm, Term, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
15TypeVisitableExt, TypingMode,
16};
17use tracing::{debug, instrument};
1819use super::{BoundVarReplacer, PlaceholderReplacer, SelectionContext, project};
20use crate::error_reporting::InferCtxtErrorExt;
21use crate::error_reporting::traits::OverflowCause;
22use crate::solve::NextSolverError;
2324impl<'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: T)
-> InferOk<'tcx, T> {
if self.infcx.next_trait_solver() {
InferOk { value, obligations: PredicateObligations::new() }
} else {
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: 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>)]25impl<'tcx> At<'_, 'tcx> {
26/// Normalize a value using the `AssocTypeNormalizer`.
27 ///
28 /// This normalization should be used when the type contains inference variables or the
29 /// projection may be fallible.
30fn normalize<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> InferOk<'tcx, T> {
31if self.infcx.next_trait_solver() {
32InferOk { value, obligations: PredicateObligations::new() }
33 } else {
34let mut selcx = SelectionContext::new(self.infcx);
35let Normalized { value, obligations } =
36normalize_with_depth(&mut selcx, self.param_env, self.cause.clone(), 0, value);
37InferOk { value, obligations }
38 }
39 }
4041/// Deeply normalizes `value`, replacing all aliases which can by normalized in
42 /// the current environment. In the new solver this errors in case normalization
43 /// fails or is ambiguous.
44 ///
45 /// In the old solver this simply uses `normalizes` and adds the nested obligations
46 /// to the `fulfill_cx`. This is necessary as we otherwise end up recomputing the
47 /// same goals in both a temporary and the shared context which negatively impacts
48 /// performance as these don't share caching.
49 ///
50 /// FIXME(-Znext-solver=no): For performance reasons, we currently reuse an existing
51 /// fulfillment context in the old solver. Once we have removed the old solver, we
52 /// can remove the `fulfill_cx` parameter on this function.
53fn deeply_normalize<T, E>(
54self,
55 value: T,
56 fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
57 ) -> Result<T, Vec<E>>
58where
59T: TypeFoldable<TyCtxt<'tcx>>,
60 E: FromSolverError<'tcx, NextSolverError<'tcx>>,
61 {
62if self.infcx.next_trait_solver() {
63crate::solve::deeply_normalize(self, value)
64 } else {
65if fulfill_cx.has_pending_obligations() {
66let pending_obligations = fulfill_cx.pending_obligations();
67span_bug!(
68pending_obligations[0].cause.span,
69"deeply_normalize should not be called with pending obligations: \
70 {pending_obligations:#?}"
71);
72 }
73let value = self74 .normalize(value)
75 .into_value_registering_obligations(self.infcx, &mut *fulfill_cx);
76let errors = fulfill_cx.evaluate_obligations_error_on_ambiguity(self.infcx);
77let value = self.infcx.resolve_vars_if_possible(value);
78if errors.is_empty() {
79Ok(value)
80 } else {
81// Drop pending obligations, since deep normalization may happen
82 // in a loop and we don't want to trigger the assertion on the next
83 // iteration due to pending ambiguous obligations we've left over.
84let _ = fulfill_cx.collect_remaining_errors(self.infcx);
85Err(errors)
86 }
87 }
88 }
89}
9091/// As `normalize`, but with a custom depth.
92pub(crate) fn normalize_with_depth<'a, 'b, 'tcx, T>(
93 selcx: &'a mut SelectionContext<'b, 'tcx>,
94 param_env: ty::ParamEnv<'tcx>,
95 cause: ObligationCause<'tcx>,
96 depth: usize,
97 value: T,
98) -> Normalized<'tcx, T>
99where
100T: TypeFoldable<TyCtxt<'tcx>>,
101{
102let mut obligations = PredicateObligations::new();
103let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations);
104Normalized { value, obligations }
105}
106107#[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(107u32),
::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:119",
"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(119u32),
::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:122",
"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(122u32),
::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:123",
"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(123u32),
::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))]108pub(crate) fn normalize_with_depth_to<'a, 'b, 'tcx, T>(
109 selcx: &'a mut SelectionContext<'b, 'tcx>,
110 param_env: ty::ParamEnv<'tcx>,
111 cause: ObligationCause<'tcx>,
112 depth: usize,
113 value: T,
114 obligations: &mut PredicateObligations<'tcx>,
115) -> T
116where
117T: TypeFoldable<TyCtxt<'tcx>>,
118{
119debug!(obligations.len = obligations.len());
120let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
121let result = ensure_sufficient_stack(|| AssocTypeNormalizer::fold(&mut normalizer, value));
122debug!(?result, obligations.len = normalizer.obligations.len());
123debug!(?normalizer.obligations,);
124 result
125}
126127pub(super) fn needs_normalization<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
128 infcx: &InferCtxt<'tcx>,
129 value: &T,
130) -> bool {
131let mut flags = ty::TypeFlags::HAS_ALIAS;
132133// Opaques are treated as rigid outside of `TypingMode::PostAnalysis`,
134 // so we can ignore those.
135match infcx.typing_mode() {
136// FIXME(#132279): We likely want to reveal opaques during post borrowck analysis
137TypingMode::Coherence138 | TypingMode::Analysis { .. }
139 | TypingMode::Borrowck { .. }
140 | TypingMode::PostBorrowckAnalysis { .. } => flags.remove(ty::TypeFlags::HAS_TY_OPAQUE),
141 TypingMode::PostAnalysis => {}
142 }
143144value.has_type_flags(flags)
145}
146147struct AssocTypeNormalizer<'a, 'b, 'tcx> {
148 selcx: &'a mut SelectionContext<'b, 'tcx>,
149 param_env: ty::ParamEnv<'tcx>,
150 cause: ObligationCause<'tcx>,
151 obligations: &'a mut PredicateObligations<'tcx>,
152 depth: usize,
153 universes: Vec<Option<ty::UniverseIndex>>,
154}
155156impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> {
157fn new(
158 selcx: &'a mut SelectionContext<'b, 'tcx>,
159 param_env: ty::ParamEnv<'tcx>,
160 cause: ObligationCause<'tcx>,
161 depth: usize,
162 obligations: &'a mut PredicateObligations<'tcx>,
163 ) -> AssocTypeNormalizer<'a, 'b, 'tcx> {
164if true {
if !!selcx.infcx.next_trait_solver() {
::core::panicking::panic("assertion failed: !selcx.infcx.next_trait_solver()")
};
};debug_assert!(!selcx.infcx.next_trait_solver());
165AssocTypeNormalizer { selcx, param_env, cause, obligations, depth, universes: ::alloc::vec::Vec::new()vec![] }
166 }
167168fn fold<T: TypeFoldable<TyCtxt<'tcx>>>(&mut self, value: T) -> T {
169let value = self.selcx.infcx.resolve_vars_if_possible(value);
170{
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:170",
"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(170u32),
::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);
171172if !!value.has_escaping_bound_vars() {
{
::core::panicking::panic_fmt(format_args!("Normalizing {0:?} without wrapping in a `Binder`",
value));
}
};assert!(
173 !value.has_escaping_bound_vars(),
174"Normalizing {value:?} without wrapping in a `Binder`"
175);
176177if !needs_normalization(self.selcx.infcx, &value) { value } else { value.fold_with(self) }
178 }
179180// FIXME(mgca): While this supports constants, it is only used for types by default right now
181x;#[instrument(level = "debug", skip(self), ret)]182fn normalize_trait_projection(&mut self, proj: AliasTerm<'tcx>) -> Term<'tcx> {
183if !proj.has_escaping_bound_vars() {
184// When we don't have escaping bound vars we can normalize ambig aliases
185 // to inference variables (done in `normalize_projection_ty`). This would
186 // be wrong if there were escaping bound vars as even if we instantiated
187 // the bound vars with placeholders, we wouldn't be able to map them back
188 // after normalization succeeded.
189 //
190 // Also, as an optimization: when we don't have escaping bound vars, we don't
191 // need to replace them with placeholders (see branch below).
192let proj = proj.fold_with(self);
193 project::normalize_projection_term(
194self.selcx,
195self.param_env,
196 proj,
197self.cause.clone(),
198self.depth,
199self.obligations,
200 )
201 } else {
202// If there are escaping bound vars, we temporarily replace the
203 // bound vars with placeholders. Note though, that in the case
204 // that we still can't project for whatever reason (e.g. self
205 // type isn't known enough), we *can't* register an obligation
206 // and return an inference variable (since then that obligation
207 // would have bound vars and that's a can of worms). Instead,
208 // we just give up and fall back to pretending like we never tried!
209 //
210 // Note: this isn't necessarily the final approach here; we may
211 // want to figure out how to register obligations with escaping vars
212 // or handle this some other way.
213let infcx = self.selcx.infcx;
214let (proj, mapped_regions, mapped_types, mapped_consts) =
215 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, proj);
216let proj = proj.fold_with(self);
217let normalized_term = project::opt_normalize_projection_term(
218self.selcx,
219self.param_env,
220 proj,
221self.cause.clone(),
222self.depth,
223self.obligations,
224 )
225 .ok()
226 .flatten()
227 .unwrap_or_else(|| proj.to_term(infcx.tcx));
228229 PlaceholderReplacer::replace_placeholders(
230 infcx,
231 mapped_regions,
232 mapped_types,
233 mapped_consts,
234&self.universes,
235 normalized_term,
236 )
237 }
238 }
239240// FIXME(mgca): While this supports constants, it is only used for types by default right now
241x;#[instrument(level = "debug", skip(self), ret)]242fn normalize_inherent_projection(&mut self, inherent: AliasTerm<'tcx>) -> Term<'tcx> {
243if !inherent.has_escaping_bound_vars() {
244// When we don't have escaping bound vars we can normalize ambig aliases
245 // to inference variables (done in `normalize_projection_ty`). This would
246 // be wrong if there were escaping bound vars as even if we instantiated
247 // the bound vars with placeholders, we wouldn't be able to map them back
248 // after normalization succeeded.
249 //
250 // Also, as an optimization: when we don't have escaping bound vars, we don't
251 // need to replace them with placeholders (see branch below).
252253let inherent = inherent.fold_with(self);
254 project::normalize_inherent_projection(
255self.selcx,
256self.param_env,
257 inherent,
258self.cause.clone(),
259self.depth,
260self.obligations,
261 )
262 } else {
263let infcx = self.selcx.infcx;
264let (inherent, mapped_regions, mapped_types, mapped_consts) =
265 BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, inherent);
266let inherent = inherent.fold_with(self);
267let inherent = project::normalize_inherent_projection(
268self.selcx,
269self.param_env,
270 inherent,
271self.cause.clone(),
272self.depth,
273self.obligations,
274 );
275276 PlaceholderReplacer::replace_placeholders(
277 infcx,
278 mapped_regions,
279 mapped_types,
280 mapped_consts,
281&self.universes,
282 inherent,
283 )
284 }
285 }
286287// FIXME(mgca): While this supports constants, it is only used for types by default right now
288x;#[instrument(level = "debug", skip(self), ret)]289fn normalize_free_alias(&mut self, free: AliasTerm<'tcx>) -> Term<'tcx> {
290let recursion_limit = self.cx().recursion_limit();
291if !recursion_limit.value_within_limit(self.depth) {
292self.selcx.infcx.err_ctxt().report_overflow_error(
293 OverflowCause::DeeplyNormalize(free.into()),
294self.cause.span,
295false,
296 |diag| {
297 diag.note(crate::fluent_generated::trait_selection_ty_alias_overflow);
298 },
299 );
300 }
301302// We don't replace bound vars in the generic arguments of the free alias with
303 // placeholders. This doesn't cause any issues as instantiating parameters with
304 // bound variables is special-cased to rewrite the debruijn index to be higher
305 // whenever we fold through a binder.
306 //
307 // However, we do replace any escaping bound vars in the resulting goals with
308 // placeholders as the trait solver does not expect to encounter escaping bound
309 // vars in obligations.
310 //
311 // FIXME(lazy_type_alias): Check how much this actually matters for perf before
312 // stabilization. This is a bit weird and generally not how we handle binders in
313 // the compiler so ideally we'd do the same boundvar->placeholder->boundvar dance
314 // that other kinds of normalization do.
315let infcx = self.selcx.infcx;
316self.obligations.extend(
317 infcx.tcx.predicates_of(free.def_id).instantiate_own(infcx.tcx, free.args).map(
318 |(mut predicate, span)| {
319if free.has_escaping_bound_vars() {
320 (predicate, ..) = BoundVarReplacer::replace_bound_vars(
321 infcx,
322&mut self.universes,
323 predicate,
324 );
325 }
326let mut cause = self.cause.clone();
327 cause.map_code(|code| ObligationCauseCode::TypeAlias(code, span, free.def_id));
328 Obligation::new(infcx.tcx, cause, self.param_env, predicate)
329 },
330 ),
331 );
332self.depth += 1;
333let res = if free.kind(infcx.tcx).is_type() {
334 infcx.tcx.type_of(free.def_id).instantiate(infcx.tcx, free.args).fold_with(self).into()
335 } else {
336 infcx
337 .tcx
338 .const_of_item(free.def_id)
339 .instantiate(infcx.tcx, free.args)
340 .fold_with(self)
341 .into()
342 };
343self.depth -= 1;
344 res
345 }
346}
347348impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx> {
349fn cx(&self) -> TyCtxt<'tcx> {
350self.selcx.tcx()
351 }
352353fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
354&mut self,
355 t: ty::Binder<'tcx, T>,
356 ) -> ty::Binder<'tcx, T> {
357self.universes.push(None);
358let t = t.super_fold_with(self);
359self.universes.pop();
360t361 }
362363fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
364if !needs_normalization(self.selcx.infcx, &ty) {
365return ty;
366 }
367368let (kind, data) = match *ty.kind() {
369 ty::Alias(kind, data) => (kind, data),
370_ => return ty.super_fold_with(self),
371 };
372373// We try to be a little clever here as a performance optimization in
374 // cases where there are nested projections under binders.
375 // For example:
376 // ```
377 // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>)
378 // ```
379 // We normalize the args on the projection before the projecting, but
380 // if we're naive, we'll
381 // replace bound vars on inner, project inner, replace placeholders on inner,
382 // replace bound vars on outer, project outer, replace placeholders on outer
383 //
384 // However, if we're a bit more clever, we can replace the bound vars
385 // on the entire type before normalizing nested projections, meaning we
386 // replace bound vars on outer, project inner,
387 // project outer, replace placeholders on outer
388 //
389 // This is possible because the inner `'a` will already be a placeholder
390 // when we need to normalize the inner projection
391 //
392 // On the other hand, this does add a bit of complexity, since we only
393 // replace bound vars if the current type is a `Projection` and we need
394 // to make sure we don't forget to fold the args regardless.
395396match kind {
397 ty::Opaque => {
398// Only normalize `impl Trait` outside of type inference, usually in codegen.
399match self.selcx.infcx.typing_mode() {
400// FIXME(#132279): We likely want to reveal opaques during post borrowck analysis
401TypingMode::Coherence402 | TypingMode::Analysis { .. }
403 | TypingMode::Borrowck { .. }
404 | TypingMode::PostBorrowckAnalysis { .. } => ty.super_fold_with(self),
405 TypingMode::PostAnalysis => {
406let recursion_limit = self.cx().recursion_limit();
407if !recursion_limit.value_within_limit(self.depth) {
408self.selcx.infcx.err_ctxt().report_overflow_error(
409 OverflowCause::DeeplyNormalize(data.into()),
410self.cause.span,
411true,
412 |_| {},
413 );
414 }
415416let args = data.args.fold_with(self);
417let generic_ty = self.cx().type_of(data.def_id);
418let concrete_ty = generic_ty.instantiate(self.cx(), args);
419self.depth += 1;
420let folded_ty = self.fold_ty(concrete_ty);
421self.depth -= 1;
422folded_ty423 }
424 }
425 }
426427 ty::Projection => self.normalize_trait_projection(data.into()).expect_type(),
428 ty::Inherent => self.normalize_inherent_projection(data.into()).expect_type(),
429 ty::Free => self.normalize_free_alias(data.into()).expect_type(),
430 }
431 }
432433#[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(433u32),
::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(uv.into()).expect_const(),
DefKind::Impl { of_trait: false } => {
self.normalize_inherent_projection(uv.into()).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(uv.into()).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")]434fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
435let tcx = self.selcx.tcx();
436437if tcx.features().generic_const_exprs()
438// Normalize type_const items even with feature `generic_const_exprs`.
439&& !matches!(ct.kind(), ty::ConstKind::Unevaluated(uv) if tcx.is_type_const(uv.def))
440 || !needs_normalization(self.selcx.infcx, &ct)
441 {
442return ct;
443 }
444445let uv = match ct.kind() {
446 ty::ConstKind::Unevaluated(uv) => uv,
447_ => return ct.super_fold_with(self),
448 };
449450// Note that the AssocConst and Const cases are unreachable on stable,
451 // unless a `min_generic_const_args` feature gate error has already
452 // been emitted earlier in compilation.
453 //
454 // That's because we can only end up with an Unevaluated ty::Const for a const item
455 // if it was marked with `#[type_const]`. Using this attribute without the mgca
456 // feature gate causes a parse error.
457let ct = match tcx.def_kind(uv.def) {
458 DefKind::AssocConst => match tcx.def_kind(tcx.parent(uv.def)) {
459 DefKind::Trait => self.normalize_trait_projection(uv.into()).expect_const(),
460 DefKind::Impl { of_trait: false } => {
461self.normalize_inherent_projection(uv.into()).expect_const()
462 }
463 kind => unreachable!(
464"unexpected `DefKind` for const alias' resolution's parent def: {:?}",
465 kind
466 ),
467 },
468 DefKind::Const => self.normalize_free_alias(uv.into()).expect_const(),
469 DefKind::AnonConst => {
470let ct = ct.super_fold_with(self);
471super::with_replaced_escaping_bound_vars(
472self.selcx.infcx,
473&mut self.universes,
474 ct,
475 |ct| super::evaluate_const(self.selcx.infcx, ct, self.param_env),
476 )
477 }
478 kind => {
479unreachable!("unexpected `DefKind` for const alias to resolve to: {:?}", kind)
480 }
481 };
482483// We re-fold the normalized const as the `ty` field on `ConstKind::Value` may be
484 // unnormalized after const evaluation returns.
485ct.super_fold_with(self)
486 }
487488#[inline]
489fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
490if p.allow_normalization() && needs_normalization(self.selcx.infcx, &p) {
491p.super_fold_with(self)
492 } else {
493p494 }
495 }
496}