1use std::collections::hash_map::Entry;
23use rustc_type_ir::inherent::*;
4use rustc_type_ir::solve::{Goal, QueryInput};
5use rustc_type_ir::{
6selfas ty, Canonical, CanonicalParamEnvCacheEntry, CanonicalVarKind, CanonicalizerState,
7Const, Flags, InferCtxtLike, Interner, PlaceholderConst, PlaceholderType, PredicateProxy,
8Region, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
9};
1011use crate::delegate::SolverDelegate;
1213/// Does this have infer/placeholder/param, free regions or ReErased?
14// We're explicitly checking for fresh types and consts to trigger an
15// assert if they ever leak into the trait solver. They should never
16// exist with the new solver.
17const NEEDS_CANONICAL: TypeFlags = TypeFlags::from_bits(
18TypeFlags::HAS_INFER.bits()
19 | TypeFlags::HAS_PLACEHOLDER.bits()
20 | TypeFlags::HAS_PARAM.bits()
21 | TypeFlags::HAS_FREE_REGIONS.bits()
22 | TypeFlags::HAS_RE_ERASED.bits()
23 | TypeFlags::HAS_TY_FRESH.bits()
24 | TypeFlags::HAS_CT_FRESH.bits(),
25)
26.unwrap();
2728#[derive(#[automatically_derived]impl<I: ::core::fmt::Debug + Interner>
::core::fmt::Debug for CanonicalizeInputKind<I> where
I::CanonicalVarKinds: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::ParamEnv =>
::core::fmt::Formatter::write_str(f, "ParamEnv"),
Self::Predicate { param_env_var_kinds: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Predicate param_env_var_kinds", &__self_0),
}
}
}Debug, #[automatically_derived]impl<I: ::core::clone::Clone + Interner>
::core::clone::Clone for CanonicalizeInputKind<I> where
I::CanonicalVarKinds: ::core::clone::Clone {
#[inline]
fn clone(&self) -> Self {
match self {
Self::ParamEnv => CanonicalizeInputKind::ParamEnv,
Self::Predicate { param_env_var_kinds: __self_0 } =>
CanonicalizeInputKind::Predicate {
param_env_var_kinds: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]impl<I: ::core::marker::Copy + Interner>
::core::marker::Copy for CanonicalizeInputKind<I> where
I::CanonicalVarKinds: ::core::marker::Copy {
}Copy)]
29enum CanonicalizeInputKind<I: Interner> {
30/// When canonicalizing the `param_env`, we keep `'static` as merging
31 /// trait candidates relies on it when deciding whether a where-bound
32 /// is trivial.
33ParamEnv,
34/// When canonicalizing predicates, we don't keep `'static`.
35 /// `param_env_var_kinds` caches the interned variable kinds to be
36 /// reused if there are no new vars.
37Predicate { param_env_var_kinds: Option<I::CanonicalVarKinds> },
38}
3940/// Whether we're canonicalizing a query input or the query response.
41///
42/// When canonicalizing an input we're in the context of the caller
43/// while canonicalizing the response happens in the context of the
44/// query.
45#[derive(#[automatically_derived]impl<I: ::core::fmt::Debug + Interner>
::core::fmt::Debug for CanonicalizeMode<I> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Input(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Input",
&__self_0),
Self::Response { max_input_universe: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Response max_input_universe", &__self_0),
}
}
}Debug, #[automatically_derived]impl<I: ::core::clone::Clone + Interner>
::core::clone::Clone for CanonicalizeMode<I> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Input(__self_0) =>
CanonicalizeMode::Input(::core::clone::Clone::clone(__self_0)),
Self::Response { max_input_universe: __self_0 } =>
CanonicalizeMode::Response {
max_input_universe: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]impl<I: ::core::marker::Copy + Interner>
::core::marker::Copy for CanonicalizeMode<I> {
}Copy)]
46enum CanonicalizeMode<I: Interner> {
47 Input(CanonicalizeInputKind<I>),
48/// FIXME: We currently return region constraints referring to
49 /// placeholders and inference variables from a binder instantiated
50 /// inside of the query.
51 ///
52 /// In the long term we should eagerly deal with these constraints
53 /// inside of the query and only propagate constraints which are
54 /// actually nameable by the caller.
55Response {
56/// The highest universe nameable by the caller.
57 ///
58 /// All variables in a universe nameable by the caller get mapped
59 /// to the root universe in the response and then mapped back to
60 /// their correct universe when applying the query response in the
61 /// context of the caller.
62 ///
63 /// This doesn't work for universes created inside of the query so
64 /// we do remember their universe in the response.
65max_input_universe: ty::UniverseIndex,
66 },
67}
6869pub(super) struct Canonicalizer<'a, D: SolverDelegate<Interner = I>, I: Interner> {
70 delegate: &'a D,
7172// Immutable field.
73canonicalize_mode: CanonicalizeMode<I>,
7475// Mutable fields.
76state: Box<CanonicalizerState<I>>,
77}
7879impl<'a, D: SolverDelegate<Interner = I>, I: Interner> Canonicalizer<'a, D, I> {
80fn new(delegate: &'a D, canonicalize_mode: CanonicalizeMode<I>) -> Self {
81Canonicalizer { delegate, canonicalize_mode, state: delegate.obtain_canonicalizer_state() }
82 }
8384pub(super) fn canonicalize_response<T: TypeFoldable<I>>(
85 delegate: &'a D,
86 max_input_universe: ty::UniverseIndex,
87 value: T,
88 ) -> ty::Canonical<I, T> {
89let mut canonicalizer =
90Canonicalizer::new(delegate, CanonicalizeMode::Response { max_input_universe });
91let value = if value.has_type_flags(NEEDS_CANONICAL) {
92value.fold_with(&mut canonicalizer)
93 } else {
94value95 };
96if true {
if !!value.has_infer() {
{
::core::panicking::panic_fmt(format_args!("unexpected infer in {0:?}",
value));
}
};
};debug_assert!(!value.has_infer(), "unexpected infer in {value:?}");
97if true {
if !!value.has_placeholders() {
{
::core::panicking::panic_fmt(format_args!("unexpected placeholders in {0:?}",
value));
}
};
};debug_assert!(!value.has_placeholders(), "unexpected placeholders in {value:?}");
98let (max_universe, var_kinds) = canonicalizer.finalize();
99100Canonical { max_universe, var_kinds, value }
101 }
102103// The return value is the canonicalized `param_env`, plus a canonicalizer suitable for
104 // canonicalizing the rest of the input. (For efficiency, and when appropriate, the returned
105 // canonicalizer will be the same one used on `param_env`, with suitable modifications.)
106fn canonicalize_param_env(delegate: &'a D, param_env: I::ParamEnv) -> (I::ParamEnv, Self) {
107if !param_env.has_type_flags(NEEDS_CANONICAL) {
108let rest_canonicalizer = Canonicalizer::new(
109delegate,
110 CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
111 param_env_var_kinds: None,
112 }),
113 );
114115return (param_env, rest_canonicalizer);
116 }
117118// Do the `env` canonicalization, and then convert the canonicalizer to `rest` form for
119 // subsequent use, also returning the optionally interned (i.e., uniquely identified)
120 // canonicalized variable kind list in case cache is used, so it can also be cached.
121let do_env_and_make_rest = |intern_var_kinds: bool| {
122let mut env_canonicalizer = Canonicalizer::new(
123delegate,
124 CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv),
125 );
126let param_env = param_env.fold_with(&mut env_canonicalizer);
127128if true {
if !env_canonicalizer.state.sub_root_lookup_table.is_empty() {
::core::panicking::panic("assertion failed: env_canonicalizer.state.sub_root_lookup_table.is_empty()")
};
};debug_assert!(env_canonicalizer.state.sub_root_lookup_table.is_empty());
129130// Transform the `env_canonicalizer` into the `rest_canonicalizer`, keeping some things
131 // and replacing others.
132 //
133 // We do not reuse the cache as it may contain entries whose canonicalized
134 // value contains `'static`. While we could alternatively handle this by
135 // checking for `'static` when using cached entries, this does not
136 // feel worth the effort. I do not expect that a `ParamEnv` will ever
137 // contain large enough types for caching to be necessary.
138 //
139 // We clear the cache rather than deleting it or replacing it with an empty cache. This
140 // lets the allocated capacity be reused later.
141let param_env_var_kinds = intern_var_kinds142 .then(|| delegate.cx().mk_canonical_var_kinds(&env_canonicalizer.state.var_kinds));
143let mut rest_canonicalizer = Canonicalizer {
144 canonicalize_mode: CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
145param_env_var_kinds,
146 }),
147 ..env_canonicalizer148 };
149rest_canonicalizer.state.cache.clear();
150151 (param_env, rest_canonicalizer, param_env_var_kinds)
152 };
153154// Check whether we can use the global cache for this param_env. As we only use
155 // the `param_env` itself as the cache key, considering any additional information
156 // during its canonicalization would be incorrect. We always canonicalize region
157 // inference variables in a separate universe, so these are fine. However, we do
158 // track the universe of type and const inference variables so these must not be
159 // globally cached. We don't rely on any additional information when canonicalizing
160 // placeholders.
161if !param_env.has_non_region_infer() {
162delegate.cx().with_canonical_param_env_cache(|cache| match cache.0.entry(param_env) {
163 Entry::Vacant(e) => {
164// Cache miss. Do `env` canonicalization and get `rest_canonicalizer`, and
165 // fill in the cache entry.
166let (param_env, rest_canonicalizer, var_kinds) = do_env_and_make_rest(true);
167e.insert(CanonicalParamEnvCacheEntry {
168param_env,
169 variables: rest_canonicalizer.state.variables.clone(),
170 var_kinds: var_kinds.unwrap(),
171// SAFETY: The iterated elements go straight back into a hashmap.
172#[allow(rustc::potential_query_instability)]
173variable_lookup_table: rest_canonicalizer174 .state
175 .variable_lookup_table
176 .iter()
177 .map(|(&arg, &idx)| (arg, idx))
178 .collect(),
179 });
180 (param_env, rest_canonicalizer)
181 }
182 Entry::Occupied(e) => {
183// Cache hit; no canonicalization required. Just set up `rest_canonicalizer`.
184let e = e.get();
185let mut rest_canonicalizer = Canonicalizer::new(
186delegate,
187 CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
188 param_env_var_kinds: Some(e.var_kinds),
189 }),
190 );
191rest_canonicalizer.state.variables.clone_from(&e.variables);
192e.var_kinds.as_slice().clone_into(&mut rest_canonicalizer.state.var_kinds);
193rest_canonicalizer194 .state
195 .variable_lookup_table
196 .clone_from(&e.variable_lookup_table);
197 (e.param_env, rest_canonicalizer)
198 }
199 })
200 } else {
201// Do `env` canonicalization and get `rest_canonicalizer`.
202let (param_env, rest_canonicalizer, _) = do_env_and_make_rest(false);
203 (param_env, rest_canonicalizer)
204 }
205 }
206207/// When canonicalizing query inputs, we keep `'static` in the `param_env`
208 /// but erase it everywhere else. We generally don't want to depend on region
209 /// identity, so while it should not matter whether `'static` is kept in the
210 /// value or opaque type storage as well, this prevents us from accidentally
211 /// relying on it in the future.
212 ///
213 /// We want to keep the option of canonicalizing `'static` to an existential
214 /// variable in the future by changing the way we detect global where-bounds.
215pub(super) fn canonicalize_input<P: TypeFoldable<I>>(
216 delegate: &'a D,
217 input: QueryInput<I, P>,
218 ) -> (Vec<I::GenericArg>, ty::Canonical<I, QueryInput<I, P>>) {
219// First canonicalize the `param_env` while keeping `'static`. This produces a
220 // canonicalizer that can canonicalize the rest of the input without keeping `'static`.
221let (param_env, mut rest_canonicalizer) =
222Self::canonicalize_param_env(delegate, input.goal.param_env);
223224let predicate = input.goal.predicate;
225let predicate = predicate.fold_with(&mut rest_canonicalizer);
226let goal = Goal { param_env, predicate };
227228let predefined_opaques_in_body = input.predefined_opaques_in_body;
229let predefined_opaques_in_body =
230if predefined_opaques_in_body.has_type_flags(NEEDS_CANONICAL) {
231predefined_opaques_in_body.fold_with(&mut rest_canonicalizer)
232 } else {
233predefined_opaques_in_body234 };
235236let value = QueryInput { goal, predefined_opaques_in_body };
237238if true {
if !!value.has_infer() {
{
::core::panicking::panic_fmt(format_args!("unexpected infer in {0:?}",
value));
}
};
};debug_assert!(!value.has_infer(), "unexpected infer in {value:?}");
239if true {
if !!value.has_placeholders() {
{
::core::panicking::panic_fmt(format_args!("unexpected placeholders in {0:?}",
value));
}
};
};debug_assert!(!value.has_placeholders(), "unexpected placeholders in {value:?}");
240let variables = rest_canonicalizer.state.variables.clone();
241let (max_universe, var_kinds) = rest_canonicalizer.finalize();
242 (variables, Canonical { max_universe, var_kinds, value })
243 }
244245fn get_or_insert_bound_var(
246&mut self,
247 arg: impl Into<I::GenericArg>,
248 kind: CanonicalVarKind<I>,
249 ) -> ty::BoundVar {
250// The exact value of 16 here doesn't matter that much (8 and 32 give extremely similar
251 // results). So long as we have protection against the rare cases where the length reaches
252 // 1000+ (e.g. `wg-grammar`).
253let arg = arg.into();
254let idx = if self.state.variables.len() > 16 {
255if self.state.variable_lookup_table.is_empty() {
256self.state
257 .variable_lookup_table
258 .extend(self.state.variables.iter().copied().zip(0..));
259 }
260261*self.state.variable_lookup_table.entry(arg).or_insert_with(|| {
262let var = self.state.variables.len();
263self.state.variables.push(arg);
264self.state.var_kinds.push(kind);
265var266 })
267 } else {
268self.state.variables.iter().position(|&v| v == arg).unwrap_or_else(|| {
269let var = self.state.variables.len();
270self.state.variables.push(arg);
271self.state.var_kinds.push(kind);
272var273 })
274 };
275276 ty::BoundVar::from(idx)
277 }
278279fn get_or_insert_sub_root(&mut self, vid: ty::TyVid) -> ty::BoundVar {
280let root_vid = self.delegate.sub_unification_table_root_var(vid);
281let idx = *self282 .state
283 .sub_root_lookup_table
284 .entry(root_vid)
285 .or_insert_with(|| self.state.variables.len());
286 ty::BoundVar::from(idx)
287 }
288289fn finalize(mut self) -> (ty::UniverseIndex, I::CanonicalVarKinds) {
290// See the rustc-dev-guide section about how we deal with universes
291 // during canonicalization in the new solver.
292let max_universe = match self.canonicalize_mode {
293// All placeholders and vars are canonicalized in the root universe.
294CanonicalizeMode::Input(_) => {
295if true {
if !self.state.var_kinds.iter().all(|var|
var.universe() == ty::UniverseIndex::ROOT) {
{
::core::panicking::panic_fmt(format_args!("expected all vars to be canonicalized in root universe: {0:#?}",
self.state.var_kinds));
}
};
};debug_assert!(
296self.state
297 .var_kinds
298 .iter()
299 .all(|var| var.universe() == ty::UniverseIndex::ROOT),
300"expected all vars to be canonicalized in root universe: {:#?}",
301self.state.var_kinds,
302 );
303 ty::UniverseIndex::ROOT304 }
305// When canonicalizing a response we map a universes already entered
306 // by the caller to the root universe and only return useful universe
307 // information for placeholders and inference variables created inside
308 // of the query.
309CanonicalizeMode::Response { max_input_universe } => {
310for var in self.state.var_kinds.iter_mut() {
311let uv = var.universe();
312let new_uv = ty::UniverseIndex::from(
313 uv.index().saturating_sub(max_input_universe.index()),
314 );
315*var = var.with_updated_universe(new_uv);
316 }
317self.state
318 .var_kinds
319 .iter()
320 .map(|kind| kind.universe())
321 .max()
322 .unwrap_or(ty::UniverseIndex::ROOT)
323 }
324 };
325let var_kinds = match self.canonicalize_mode {
326 CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
327 param_env_var_kinds: Some(cached),
328 }) if cached.len() == self.state.variables.len() => {
329if true {
{
match (&cached.as_slice(), &self.state.var_kinds.as_slice()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(cached.as_slice(), self.state.var_kinds.as_slice());
330cached331 }
332_ => self.delegate.cx().mk_canonical_var_kinds(&self.state.var_kinds),
333 };
334335// We have finished with this canonicalizer and can return its state to the delegate for
336 // later reuse.
337self.delegate.release_canonicalizer_state(self.state);
338339 (max_universe, var_kinds)
340 }
341342fn inner_fold_ty(&mut self, t: I::Ty) -> I::Ty {
343let kind = match t.kind() {
344 ty::Infer(i) => match i {
345 ty::TyVar(vid) => {
346if true {
{
match (&self.delegate.shallow_resolve_ty_var(vid), &t) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("ty vid should have been resolved fully before canonicalization")));
}
}
}
};
};debug_assert_eq!(
347self.delegate.shallow_resolve_ty_var(vid),
348 t,
349"ty vid should have been resolved fully before canonicalization"
350);
351352let sub_root = self.get_or_insert_sub_root(vid);
353let ui = match self.canonicalize_mode {
354 CanonicalizeMode::Input(_) => ty::UniverseIndex::ROOT,
355 CanonicalizeMode::Response { .. } => self356 .delegate
357 .universe_of_ty(vid)
358 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("ty var should have been resolved: {0:?}",
t));
}panic!("ty var should have been resolved: {t:?}")),
359 };
360 CanonicalVarKind::Ty { ui, sub_root }
361 }
362 ty::IntVar(vid) => {
363if true {
{
match (&self.delegate.shallow_resolve_int_var(vid), &t) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("ty vid should have been resolved fully before canonicalization")));
}
}
}
};
};debug_assert_eq!(
364self.delegate.shallow_resolve_int_var(vid),
365 t,
366"ty vid should have been resolved fully before canonicalization"
367);
368 CanonicalVarKind::Int369 }
370 ty::FloatVar(vid) => {
371if true {
{
match (&self.delegate.shallow_resolve_float_var(vid), &t) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("ty vid should have been resolved fully before canonicalization")));
}
}
}
};
};debug_assert_eq!(
372self.delegate.shallow_resolve_float_var(vid),
373 t,
374"ty vid should have been resolved fully before canonicalization"
375);
376 CanonicalVarKind::Float377 }
378 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => {
379{
::core::panicking::panic_fmt(format_args!("fresh vars not expected in canonicalization"));
}panic!("fresh vars not expected in canonicalization")380 }
381 },
382 ty::Placeholder(placeholder) => match self.canonicalize_mode {
383 CanonicalizeMode::Input(_) => {
384 CanonicalVarKind::PlaceholderTy(PlaceholderType::new_anon(
385 ty::UniverseIndex::ROOT,
386self.state.variables.len().into(),
387 ))
388 }
389 CanonicalizeMode::Response { .. } => CanonicalVarKind::PlaceholderTy(placeholder),
390 },
391 ty::Param(_) => match self.canonicalize_mode {
392 CanonicalizeMode::Input(_) => {
393 CanonicalVarKind::PlaceholderTy(PlaceholderType::new_anon(
394 ty::UniverseIndex::ROOT,
395self.state.variables.len().into(),
396 ))
397 }
398 CanonicalizeMode::Response { .. } => {
::core::panicking::panic_fmt(format_args!("param ty in response: {0:?}",
t));
}panic!("param ty in response: {t:?}"),
399 },
400 ty::Bool401 | ty::Char402 | ty::Int(_)
403 | ty::Uint(_)
404 | ty::Float(_)
405 | ty::Adt(_, _)
406 | ty::Foreign(_)
407 | ty::Str408 | ty::Array(_, _)
409 | ty::Slice(_)
410 | ty::RawPtr(_, _)
411 | ty::Ref(_, _, _)
412 | ty::Pat(_, _)
413 | ty::FnDef(_, _)
414 | ty::FnPtr(..)
415 | ty::UnsafeBinder(_)
416 | ty::Dynamic(_, _)
417 | ty::Closure(..)
418 | ty::CoroutineClosure(..)
419 | ty::Coroutine(_, _)
420 | ty::CoroutineWitness(..)
421 | ty::Never422 | ty::Tuple(_)
423 | ty::Alias(_, _)
424 | ty::Bound(_, _)
425 | ty::Error(_) => {
426return t.super_fold_with(self);
427 }
428 };
429430let var = self.get_or_insert_bound_var(t, kind);
431432 Ty::new_canonical_bound(self.cx(), var)
433 }
434}
435436impl<D: SolverDelegate<Interner = I>, I: Interner> TypeFolder<I> for Canonicalizer<'_, D, I> {
437fn cx(&self) -> I {
438self.delegate.cx()
439 }
440441fn fold_region(&mut self, r: Region<I>) -> Region<I> {
442// We canonicalize free regions from the input into placeholder regions so that
443 // region constraints created in nested contexts can be propagated back to the
444 // caller, instead of unifying them.
445 // See the following Zulip discussion for details:
446 // https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/A.20question.20on.20.23251/near/579240238
447let kind = match r.kind() {
448 ty::ReBound(..) => return r,
449450// We don't canonicalize `ReStatic` in the `param_env` as we use it
451 // when checking whether a `ParamEnv` candidate is global.
452ty::ReStatic => match self.canonicalize_mode {
453 CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { .. }) => {
454 CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
455 ty::UniverseIndex::ROOT,
456self.state.variables.len().into(),
457 ))
458 }
459 CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv)
460 | CanonicalizeMode::Response { .. } => return r,
461 },
462463// `ReErased` should only be encountered in the hidden
464 // type of an opaque for regions that are ignored for the purposes of
465 // captures.
466 //
467 // FIXME: We should investigate the perf implications of not uniquifying
468 // `ReErased`. We may be able to short-circuit registering region
469 // obligations if we encounter a `ReErased` on one side, for example.
470ty::ReErased | ty::ReError(_) => match self.canonicalize_mode {
471 CanonicalizeMode::Input(_) => {
472 CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
473 ty::UniverseIndex::ROOT,
474self.state.variables.len().into(),
475 ))
476 }
477 CanonicalizeMode::Response { .. } => return r,
478 },
479480 ty::ReEarlyParam(_) | ty::ReLateParam(_) => match self.canonicalize_mode {
481 CanonicalizeMode::Input(_) => {
482 CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
483 ty::UniverseIndex::ROOT,
484self.state.variables.len().into(),
485 ))
486 }
487 CanonicalizeMode::Response { .. } => {
488{
::core::panicking::panic_fmt(format_args!("unexpected region in response: {0:?}",
r));
}panic!("unexpected region in response: {r:?}")489 }
490 },
491492 ty::RePlaceholder(placeholder) => match self.canonicalize_mode {
493 CanonicalizeMode::Input(_) => {
494 CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
495 ty::UniverseIndex::ROOT,
496self.state.variables.len().into(),
497 ))
498 }
499 CanonicalizeMode::Response { max_input_universe } => {
500// If we have a placeholder region inside of a query, it must be from
501 // a new universe, unless from the root universe, which is used for
502 // canonicalization of any free region from the input.
503if placeholder.universe() != ty::UniverseIndex::ROOT504 && max_input_universe.can_name(placeholder.universe())
505 {
506{
::core::panicking::panic_fmt(format_args!("new placeholder in universe {0:?}: {1:?}",
max_input_universe, r));
};panic!("new placeholder in universe {max_input_universe:?}: {r:?}");
507 }
508 CanonicalVarKind::PlaceholderRegion(placeholder)
509 }
510 },
511512 ty::ReVar(vid) => {
513if true {
{
match (&self.delegate.shallow_resolve_region_var(vid), &r) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("region vid should have been resolved fully before canonicalization")));
}
}
}
};
};debug_assert_eq!(
514self.delegate.shallow_resolve_region_var(vid),
515 r,
516"region vid should have been resolved fully before canonicalization"
517);
518match self.canonicalize_mode {
519 CanonicalizeMode::Input(_) => {
520 CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
521 ty::UniverseIndex::ROOT,
522self.state.variables.len().into(),
523 ))
524 }
525 CanonicalizeMode::Response { .. } => {
526 CanonicalVarKind::Region(self.delegate.universe_of_region(vid).unwrap())
527 }
528 }
529 }
530 };
531532let var = self.get_or_insert_bound_var(r, kind);
533534Region::new_canonical_bound(self.cx(), var)
535 }
536537fn fold_ty(&mut self, t: I::Ty) -> I::Ty {
538if !t.flags().intersects(NEEDS_CANONICAL) {
539t540 } else if let Some(&ty) = self.state.cache.get(&t) {
541ty542 } else {
543let res = self.inner_fold_ty(t);
544let is_unseen = self.state.cache.insert(t, res);
545if !is_unseen { ::core::panicking::panic("assertion failed: is_unseen") };assert!(is_unseen);
546res547 }
548 }
549550fn fold_const(&mut self, c: Const<I>) -> Const<I> {
551if !c.flags().intersects(NEEDS_CANONICAL) {
552return c;
553 }
554555let kind = match c.kind() {
556 ty::ConstKind::Infer(i) => match i {
557 ty::InferConst::Var(vid) => {
558if true {
{
match (&self.delegate.shallow_resolve_const_var(vid), &c) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("const vid should have been resolved fully before canonicalization")));
}
}
}
};
};debug_assert_eq!(
559self.delegate.shallow_resolve_const_var(vid),
560 c,
561"const vid should have been resolved fully before canonicalization"
562);
563564match self.canonicalize_mode {
565 CanonicalizeMode::Input(_) => {
566 CanonicalVarKind::Const(ty::UniverseIndex::ROOT)
567 }
568 CanonicalizeMode::Response { .. } => {
569 CanonicalVarKind::Const(self.delegate.universe_of_const(vid).unwrap())
570 }
571 }
572 }
573 ty::InferConst::Fresh(_) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
574 },
575 ty::ConstKind::Placeholder(placeholder) => match self.canonicalize_mode {
576 CanonicalizeMode::Input(_) => {
577 CanonicalVarKind::PlaceholderConst(PlaceholderConst::new_anon(
578 ty::UniverseIndex::ROOT,
579self.state.variables.len().into(),
580 ))
581 }
582 CanonicalizeMode::Response { .. } => {
583 CanonicalVarKind::PlaceholderConst(placeholder)
584 }
585 },
586 ty::ConstKind::Param(_) => match self.canonicalize_mode {
587 CanonicalizeMode::Input(_) => {
588 CanonicalVarKind::PlaceholderConst(PlaceholderConst::new_anon(
589 ty::UniverseIndex::ROOT,
590self.state.variables.len().into(),
591 ))
592 }
593 CanonicalizeMode::Response { .. } => {
::core::panicking::panic_fmt(format_args!("param ty in response: {0:?}",
c));
}panic!("param ty in response: {c:?}"),
594 },
595// FIXME: See comment above -- we could fold the region separately or something.
596ty::ConstKind::Bound(_, _)
597 | ty::ConstKind::Alias(_, _)
598 | ty::ConstKind::Value(_)
599 | ty::ConstKind::Error(_)
600 | ty::ConstKind::Expr(_) => return c.super_fold_with(self),
601 };
602603let var = self.get_or_insert_bound_var(c, kind);
604605Const::new_canonical_bound(self.cx(), var)
606 }
607608fn fold_predicate<P: PredicateProxy<I>>(&mut self, p: P) -> P {
609if !p.flags().intersects(NEEDS_CANONICAL) { p } else { p.super_fold_with(self) }
610 }
611612fn fold_clauses(&mut self, c: I::Clauses) -> I::Clauses {
613match self.canonicalize_mode {
614 CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv)
615 | CanonicalizeMode::Response { max_input_universe: _ } => {}
616 CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { .. }) => {
617{ ::core::panicking::panic_fmt(format_args!("erasing \'static in env")); }panic!("erasing 'static in env")618 }
619 }
620if !c.flags().intersects(NEEDS_CANONICAL) { c } else { c.super_fold_with(self) }
621 }
622}