Skip to main content

rustc_next_trait_solver/canonical/
canonicalizer.rs

1use std::collections::hash_map::Entry;
2
3use rustc_type_ir::inherent::*;
4use rustc_type_ir::solve::{Goal, QueryInput};
5use rustc_type_ir::{
6    self as ty, Canonical, CanonicalParamEnvCacheEntry, CanonicalVarKind, CanonicalizerState,
7    Const, Flags, InferCtxtLike, Interner, PlaceholderConst, PlaceholderType, PredicateProxy,
8    Region, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
9};
10
11use crate::delegate::SolverDelegate;
12
13/// 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(
18    TypeFlags::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();
27
28#[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.
33    ParamEnv,
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.
37    Predicate { param_env_var_kinds: Option<I::CanonicalVarKinds> },
38}
39
40/// 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.
55    Response {
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.
65        max_input_universe: ty::UniverseIndex,
66    },
67}
68
69pub(super) struct Canonicalizer<'a, D: SolverDelegate<Interner = I>, I: Interner> {
70    delegate: &'a D,
71
72    // Immutable field.
73    canonicalize_mode: CanonicalizeMode<I>,
74
75    // Mutable fields.
76    state: Box<CanonicalizerState<I>>,
77}
78
79impl<'a, D: SolverDelegate<Interner = I>, I: Interner> Canonicalizer<'a, D, I> {
80    fn new(delegate: &'a D, canonicalize_mode: CanonicalizeMode<I>) -> Self {
81        Canonicalizer { delegate, canonicalize_mode, state: delegate.obtain_canonicalizer_state() }
82    }
83
84    pub(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> {
89        let mut canonicalizer =
90            Canonicalizer::new(delegate, CanonicalizeMode::Response { max_input_universe });
91        let value = if value.has_type_flags(NEEDS_CANONICAL) {
92            value.fold_with(&mut canonicalizer)
93        } else {
94            value
95        };
96        if 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:?}");
97        if 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:?}");
98        let (max_universe, var_kinds) = canonicalizer.finalize();
99
100        Canonical { max_universe, var_kinds, value }
101    }
102
103    // 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.)
106    fn canonicalize_param_env(delegate: &'a D, param_env: I::ParamEnv) -> (I::ParamEnv, Self) {
107        if !param_env.has_type_flags(NEEDS_CANONICAL) {
108            let rest_canonicalizer = Canonicalizer::new(
109                delegate,
110                CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
111                    param_env_var_kinds: None,
112                }),
113            );
114
115            return (param_env, rest_canonicalizer);
116        }
117
118        // 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.
121        let do_env_and_make_rest = |intern_var_kinds: bool| {
122            let mut env_canonicalizer = Canonicalizer::new(
123                delegate,
124                CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv),
125            );
126            let param_env = param_env.fold_with(&mut env_canonicalizer);
127
128            if 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());
129
130            // 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.
141            let param_env_var_kinds = intern_var_kinds
142                .then(|| delegate.cx().mk_canonical_var_kinds(&env_canonicalizer.state.var_kinds));
143            let mut rest_canonicalizer = Canonicalizer {
144                canonicalize_mode: CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
145                    param_env_var_kinds,
146                }),
147                ..env_canonicalizer
148            };
149            rest_canonicalizer.state.cache.clear();
150
151            (param_env, rest_canonicalizer, param_env_var_kinds)
152        };
153
154        // 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.
161        if !param_env.has_non_region_infer() {
162            delegate.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.
166                    let (param_env, rest_canonicalizer, var_kinds) = do_env_and_make_rest(true);
167                    e.insert(CanonicalParamEnvCacheEntry {
168                        param_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)]
173                        variable_lookup_table: rest_canonicalizer
174                            .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`.
184                    let e = e.get();
185                    let mut rest_canonicalizer = Canonicalizer::new(
186                        delegate,
187                        CanonicalizeMode::Input(CanonicalizeInputKind::Predicate {
188                            param_env_var_kinds: Some(e.var_kinds),
189                        }),
190                    );
191                    rest_canonicalizer.state.variables.clone_from(&e.variables);
192                    e.var_kinds.as_slice().clone_into(&mut rest_canonicalizer.state.var_kinds);
193                    rest_canonicalizer
194                        .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`.
202            let (param_env, rest_canonicalizer, _) = do_env_and_make_rest(false);
203            (param_env, rest_canonicalizer)
204        }
205    }
206
207    /// 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.
215    pub(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`.
221        let (param_env, mut rest_canonicalizer) =
222            Self::canonicalize_param_env(delegate, input.goal.param_env);
223
224        let predicate = input.goal.predicate;
225        let predicate = predicate.fold_with(&mut rest_canonicalizer);
226        let goal = Goal { param_env, predicate };
227
228        let predefined_opaques_in_body = input.predefined_opaques_in_body;
229        let predefined_opaques_in_body =
230            if predefined_opaques_in_body.has_type_flags(NEEDS_CANONICAL) {
231                predefined_opaques_in_body.fold_with(&mut rest_canonicalizer)
232            } else {
233                predefined_opaques_in_body
234            };
235
236        let value = QueryInput { goal, predefined_opaques_in_body };
237
238        if 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:?}");
239        if 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:?}");
240        let variables = rest_canonicalizer.state.variables.clone();
241        let (max_universe, var_kinds) = rest_canonicalizer.finalize();
242        (variables, Canonical { max_universe, var_kinds, value })
243    }
244
245    fn 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`).
253        let arg = arg.into();
254        let idx = if self.state.variables.len() > 16 {
255            if self.state.variable_lookup_table.is_empty() {
256                self.state
257                    .variable_lookup_table
258                    .extend(self.state.variables.iter().copied().zip(0..));
259            }
260
261            *self.state.variable_lookup_table.entry(arg).or_insert_with(|| {
262                let var = self.state.variables.len();
263                self.state.variables.push(arg);
264                self.state.var_kinds.push(kind);
265                var
266            })
267        } else {
268            self.state.variables.iter().position(|&v| v == arg).unwrap_or_else(|| {
269                let var = self.state.variables.len();
270                self.state.variables.push(arg);
271                self.state.var_kinds.push(kind);
272                var
273            })
274        };
275
276        ty::BoundVar::from(idx)
277    }
278
279    fn get_or_insert_sub_root(&mut self, vid: ty::TyVid) -> ty::BoundVar {
280        let root_vid = self.delegate.sub_unification_table_root_var(vid);
281        let idx = *self
282            .state
283            .sub_root_lookup_table
284            .entry(root_vid)
285            .or_insert_with(|| self.state.variables.len());
286        ty::BoundVar::from(idx)
287    }
288
289    fn 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.
292        let max_universe = match self.canonicalize_mode {
293            // All placeholders and vars are canonicalized in the root universe.
294            CanonicalizeMode::Input(_) => {
295                if 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!(
296                    self.state
297                        .var_kinds
298                        .iter()
299                        .all(|var| var.universe() == ty::UniverseIndex::ROOT),
300                    "expected all vars to be canonicalized in root universe: {:#?}",
301                    self.state.var_kinds,
302                );
303                ty::UniverseIndex::ROOT
304            }
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.
309            CanonicalizeMode::Response { max_input_universe } => {
310                for var in self.state.var_kinds.iter_mut() {
311                    let uv = var.universe();
312                    let new_uv = ty::UniverseIndex::from(
313                        uv.index().saturating_sub(max_input_universe.index()),
314                    );
315                    *var = var.with_updated_universe(new_uv);
316                }
317                self.state
318                    .var_kinds
319                    .iter()
320                    .map(|kind| kind.universe())
321                    .max()
322                    .unwrap_or(ty::UniverseIndex::ROOT)
323            }
324        };
325        let 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() => {
329                if 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());
330                cached
331            }
332            _ => self.delegate.cx().mk_canonical_var_kinds(&self.state.var_kinds),
333        };
334
335        // We have finished with this canonicalizer and can return its state to the delegate for
336        // later reuse.
337        self.delegate.release_canonicalizer_state(self.state);
338
339        (max_universe, var_kinds)
340    }
341
342    fn inner_fold_ty(&mut self, t: I::Ty) -> I::Ty {
343        let kind = match t.kind() {
344            ty::Infer(i) => match i {
345                ty::TyVar(vid) => {
346                    if 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!(
347                        self.delegate.shallow_resolve_ty_var(vid),
348                        t,
349                        "ty vid should have been resolved fully before canonicalization"
350                    );
351
352                    let sub_root = self.get_or_insert_sub_root(vid);
353                    let ui = match self.canonicalize_mode {
354                        CanonicalizeMode::Input(_) => ty::UniverseIndex::ROOT,
355                        CanonicalizeMode::Response { .. } => self
356                            .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) => {
363                    if 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!(
364                        self.delegate.shallow_resolve_int_var(vid),
365                        t,
366                        "ty vid should have been resolved fully before canonicalization"
367                    );
368                    CanonicalVarKind::Int
369                }
370                ty::FloatVar(vid) => {
371                    if 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!(
372                        self.delegate.shallow_resolve_float_var(vid),
373                        t,
374                        "ty vid should have been resolved fully before canonicalization"
375                    );
376                    CanonicalVarKind::Float
377                }
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,
386                        self.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,
395                        self.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::Bool
401            | ty::Char
402            | ty::Int(_)
403            | ty::Uint(_)
404            | ty::Float(_)
405            | ty::Adt(_, _)
406            | ty::Foreign(_)
407            | ty::Str
408            | 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::Never
422            | ty::Tuple(_)
423            | ty::Alias(_, _)
424            | ty::Bound(_, _)
425            | ty::Error(_) => {
426                return t.super_fold_with(self);
427            }
428        };
429
430        let var = self.get_or_insert_bound_var(t, kind);
431
432        Ty::new_canonical_bound(self.cx(), var)
433    }
434}
435
436impl<D: SolverDelegate<Interner = I>, I: Interner> TypeFolder<I> for Canonicalizer<'_, D, I> {
437    fn cx(&self) -> I {
438        self.delegate.cx()
439    }
440
441    fn 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
447        let kind = match r.kind() {
448            ty::ReBound(..) => return r,
449
450            // We don't canonicalize `ReStatic` in the `param_env` as we use it
451            // when checking whether a `ParamEnv` candidate is global.
452            ty::ReStatic => match self.canonicalize_mode {
453                CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { .. }) => {
454                    CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
455                        ty::UniverseIndex::ROOT,
456                        self.state.variables.len().into(),
457                    ))
458                }
459                CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv)
460                | CanonicalizeMode::Response { .. } => return r,
461            },
462
463            // `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.
470            ty::ReErased | ty::ReError(_) => match self.canonicalize_mode {
471                CanonicalizeMode::Input(_) => {
472                    CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
473                        ty::UniverseIndex::ROOT,
474                        self.state.variables.len().into(),
475                    ))
476                }
477                CanonicalizeMode::Response { .. } => return r,
478            },
479
480            ty::ReEarlyParam(_) | ty::ReLateParam(_) => match self.canonicalize_mode {
481                CanonicalizeMode::Input(_) => {
482                    CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
483                        ty::UniverseIndex::ROOT,
484                        self.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            },
491
492            ty::RePlaceholder(placeholder) => match self.canonicalize_mode {
493                CanonicalizeMode::Input(_) => {
494                    CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
495                        ty::UniverseIndex::ROOT,
496                        self.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.
503                    if placeholder.universe() != ty::UniverseIndex::ROOT
504                        && 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            },
511
512            ty::ReVar(vid) => {
513                if 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!(
514                    self.delegate.shallow_resolve_region_var(vid),
515                    r,
516                    "region vid should have been resolved fully before canonicalization"
517                );
518                match self.canonicalize_mode {
519                    CanonicalizeMode::Input(_) => {
520                        CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new_anon(
521                            ty::UniverseIndex::ROOT,
522                            self.state.variables.len().into(),
523                        ))
524                    }
525                    CanonicalizeMode::Response { .. } => {
526                        CanonicalVarKind::Region(self.delegate.universe_of_region(vid).unwrap())
527                    }
528                }
529            }
530        };
531
532        let var = self.get_or_insert_bound_var(r, kind);
533
534        Region::new_canonical_bound(self.cx(), var)
535    }
536
537    fn fold_ty(&mut self, t: I::Ty) -> I::Ty {
538        if !t.flags().intersects(NEEDS_CANONICAL) {
539            t
540        } else if let Some(&ty) = self.state.cache.get(&t) {
541            ty
542        } else {
543            let res = self.inner_fold_ty(t);
544            let is_unseen = self.state.cache.insert(t, res);
545            if !is_unseen { ::core::panicking::panic("assertion failed: is_unseen") };assert!(is_unseen);
546            res
547        }
548    }
549
550    fn fold_const(&mut self, c: Const<I>) -> Const<I> {
551        if !c.flags().intersects(NEEDS_CANONICAL) {
552            return c;
553        }
554
555        let kind = match c.kind() {
556            ty::ConstKind::Infer(i) => match i {
557                ty::InferConst::Var(vid) => {
558                    if 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!(
559                        self.delegate.shallow_resolve_const_var(vid),
560                        c,
561                        "const vid should have been resolved fully before canonicalization"
562                    );
563
564                    match 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,
579                        self.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,
590                        self.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.
596            ty::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        };
602
603        let var = self.get_or_insert_bound_var(c, kind);
604
605        Const::new_canonical_bound(self.cx(), var)
606    }
607
608    fn fold_predicate<P: PredicateProxy<I>>(&mut self, p: P) -> P {
609        if !p.flags().intersects(NEEDS_CANONICAL) { p } else { p.super_fold_with(self) }
610    }
611
612    fn fold_clauses(&mut self, c: I::Clauses) -> I::Clauses {
613        match 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        }
620        if !c.flags().intersects(NEEDS_CANONICAL) { c } else { c.super_fold_with(self) }
621    }
622}