rustc_type_ir/
interner.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::ops::Deref;
4
5use rustc_ast_ir::Movability;
6use rustc_index::bit_set::DenseBitSet;
7
8use crate::fold::TypeFoldable;
9use crate::inherent::*;
10use crate::ir_print::IrPrint;
11use crate::lang_items::TraitSolverLangItem;
12use crate::relate::Relate;
13use crate::solve::{CanonicalInput, ExternalConstraintsData, PredefinedOpaquesData, QueryResult};
14use crate::visit::{Flags, TypeVisitable};
15use crate::{self as ty, CanonicalParamEnvCacheEntry, search_graph};
16
17#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_interner")]
18pub trait Interner:
19    Sized
20    + Copy
21    + IrPrint<ty::AliasTy<Self>>
22    + IrPrint<ty::AliasTerm<Self>>
23    + IrPrint<ty::TraitRef<Self>>
24    + IrPrint<ty::TraitPredicate<Self>>
25    + IrPrint<ty::HostEffectPredicate<Self>>
26    + IrPrint<ty::ExistentialTraitRef<Self>>
27    + IrPrint<ty::ExistentialProjection<Self>>
28    + IrPrint<ty::ProjectionPredicate<Self>>
29    + IrPrint<ty::NormalizesTo<Self>>
30    + IrPrint<ty::SubtypePredicate<Self>>
31    + IrPrint<ty::CoercePredicate<Self>>
32    + IrPrint<ty::FnSig<Self>>
33    + IrPrint<ty::PatternKind<Self>>
34{
35    fn next_trait_solver_globally(self) -> bool {
36        true
37    }
38
39    type DefId: DefId<Self>;
40    type LocalDefId: Copy + Debug + Hash + Eq + Into<Self::DefId> + TypeFoldable<Self>;
41    type Span: Span<Self>;
42
43    type GenericArgs: GenericArgs<Self>;
44    type GenericArgsSlice: Copy + Debug + Hash + Eq + SliceLike<Item = Self::GenericArg>;
45    type GenericArg: GenericArg<Self>;
46    type Term: Term<Self>;
47
48    type BoundVarKinds: Copy + Debug + Hash + Eq + SliceLike<Item = Self::BoundVarKind> + Default;
49    type BoundVarKind: Copy + Debug + Hash + Eq;
50
51    type PredefinedOpaques: Copy
52        + Debug
53        + Hash
54        + Eq
55        + TypeFoldable<Self>
56        + Deref<Target = PredefinedOpaquesData<Self>>;
57    fn mk_predefined_opaques_in_body(
58        self,
59        data: PredefinedOpaquesData<Self>,
60    ) -> Self::PredefinedOpaques;
61
62    type LocalDefIds: Copy
63        + Debug
64        + Hash
65        + Default
66        + Eq
67        + TypeVisitable<Self>
68        + SliceLike<Item = Self::LocalDefId>;
69
70    type CanonicalVarKinds: Copy
71        + Debug
72        + Hash
73        + Eq
74        + SliceLike<Item = ty::CanonicalVarKind<Self>>
75        + Default;
76    fn mk_canonical_var_kinds(
77        self,
78        kinds: &[ty::CanonicalVarKind<Self>],
79    ) -> Self::CanonicalVarKinds;
80
81    type ExternalConstraints: Copy
82        + Debug
83        + Hash
84        + Eq
85        + TypeFoldable<Self>
86        + Deref<Target = ExternalConstraintsData<Self>>;
87    fn mk_external_constraints(
88        self,
89        data: ExternalConstraintsData<Self>,
90    ) -> Self::ExternalConstraints;
91
92    type DepNodeIndex;
93    type Tracked<T: Debug + Clone>: Debug;
94    fn mk_tracked<T: Debug + Clone>(
95        self,
96        data: T,
97        dep_node: Self::DepNodeIndex,
98    ) -> Self::Tracked<T>;
99    fn get_tracked<T: Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T;
100    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, Self::DepNodeIndex);
101
102    // Kinds of tys
103    type Ty: Ty<Self>;
104    type Tys: Tys<Self>;
105    type FnInputTys: Copy + Debug + Hash + Eq + SliceLike<Item = Self::Ty> + TypeVisitable<Self>;
106    type ParamTy: ParamLike;
107    type BoundTy: BoundVarLike<Self>;
108    type PlaceholderTy: PlaceholderLike<Self, Bound = Self::BoundTy>;
109
110    // Things stored inside of tys
111    type ErrorGuaranteed: Copy + Debug + Hash + Eq;
112    type BoundExistentialPredicates: BoundExistentialPredicates<Self>;
113    type AllocId: Copy + Debug + Hash + Eq;
114    type Pat: Copy
115        + Debug
116        + Hash
117        + Eq
118        + Debug
119        + Relate<Self>
120        + Flags
121        + IntoKind<Kind = ty::PatternKind<Self>>;
122    type PatList: Copy
123        + Debug
124        + Hash
125        + Default
126        + Eq
127        + TypeVisitable<Self>
128        + SliceLike<Item = Self::Pat>;
129    type Safety: Safety<Self>;
130    type Abi: Abi<Self>;
131
132    // Kinds of consts
133    type Const: Const<Self>;
134    type ParamConst: Copy + Debug + Hash + Eq + ParamLike;
135    type BoundConst: BoundVarLike<Self>;
136    type PlaceholderConst: PlaceholderConst<Self>;
137    type ValueConst: ValueConst<Self>;
138    type ExprConst: ExprConst<Self>;
139    type ValTree: Copy + Debug + Hash + Eq;
140
141    // Kinds of regions
142    type Region: Region<Self>;
143    type EarlyParamRegion: ParamLike;
144    type LateParamRegion: Copy + Debug + Hash + Eq;
145    type BoundRegion: BoundVarLike<Self>;
146    type PlaceholderRegion: PlaceholderLike<Self, Bound = Self::BoundRegion>;
147
148    // Predicates
149    type ParamEnv: ParamEnv<Self>;
150    type Predicate: Predicate<Self>;
151    type Clause: Clause<Self>;
152    type Clauses: Clauses<Self>;
153
154    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R;
155
156    fn canonical_param_env_cache_get_or_insert<R>(
157        self,
158        param_env: Self::ParamEnv,
159        f: impl FnOnce() -> CanonicalParamEnvCacheEntry<Self>,
160        from_entry: impl FnOnce(&CanonicalParamEnvCacheEntry<Self>) -> R,
161    ) -> R;
162
163    fn evaluation_is_concurrent(&self) -> bool;
164
165    fn expand_abstract_consts<T: TypeFoldable<Self>>(self, t: T) -> T;
166
167    type GenericsOf: GenericsOf<Self>;
168    fn generics_of(self, def_id: Self::DefId) -> Self::GenericsOf;
169
170    type VariancesOf: Copy + Debug + SliceLike<Item = ty::Variance>;
171    fn variances_of(self, def_id: Self::DefId) -> Self::VariancesOf;
172
173    fn opt_alias_variances(
174        self,
175        kind: impl Into<ty::AliasTermKind>,
176        def_id: Self::DefId,
177    ) -> Option<Self::VariancesOf>;
178
179    fn type_of(self, def_id: Self::DefId) -> ty::EarlyBinder<Self, Self::Ty>;
180    fn type_of_opaque_hir_typeck(self, def_id: Self::LocalDefId)
181    -> ty::EarlyBinder<Self, Self::Ty>;
182
183    type AdtDef: AdtDef<Self>;
184    fn adt_def(self, adt_def_id: Self::DefId) -> Self::AdtDef;
185
186    fn alias_ty_kind(self, alias: ty::AliasTy<Self>) -> ty::AliasTyKind;
187
188    fn alias_term_kind(self, alias: ty::AliasTerm<Self>) -> ty::AliasTermKind;
189
190    fn trait_ref_and_own_args_for_alias(
191        self,
192        def_id: Self::DefId,
193        args: Self::GenericArgs,
194    ) -> (ty::TraitRef<Self>, Self::GenericArgsSlice);
195
196    fn mk_args(self, args: &[Self::GenericArg]) -> Self::GenericArgs;
197
198    fn mk_args_from_iter<I, T>(self, args: I) -> T::Output
199    where
200        I: Iterator<Item = T>,
201        T: CollectAndApply<Self::GenericArg, Self::GenericArgs>;
202
203    fn check_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs) -> bool;
204
205    fn debug_assert_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs);
206
207    /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection`
208    /// are compatible with the `DefId`.
209    fn debug_assert_existential_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs);
210
211    fn mk_type_list_from_iter<I, T>(self, args: I) -> T::Output
212    where
213        I: Iterator<Item = T>,
214        T: CollectAndApply<Self::Ty, Self::Tys>;
215
216    fn parent(self, def_id: Self::DefId) -> Self::DefId;
217
218    fn recursion_limit(self) -> usize;
219
220    type Features: Features<Self>;
221    fn features(self) -> Self::Features;
222
223    fn coroutine_hidden_types(
224        self,
225        def_id: Self::DefId,
226    ) -> ty::EarlyBinder<Self, ty::Binder<Self, ty::CoroutineWitnessTypes<Self>>>;
227
228    fn fn_sig(
229        self,
230        def_id: Self::DefId,
231    ) -> ty::EarlyBinder<Self, ty::Binder<Self, ty::FnSig<Self>>>;
232
233    fn coroutine_movability(self, def_id: Self::DefId) -> Movability;
234
235    fn coroutine_for_closure(self, def_id: Self::DefId) -> Self::DefId;
236
237    fn generics_require_sized_self(self, def_id: Self::DefId) -> bool;
238
239    fn item_bounds(
240        self,
241        def_id: Self::DefId,
242    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
243
244    fn item_self_bounds(
245        self,
246        def_id: Self::DefId,
247    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
248
249    fn item_non_self_bounds(
250        self,
251        def_id: Self::DefId,
252    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
253
254    fn predicates_of(
255        self,
256        def_id: Self::DefId,
257    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
258
259    fn own_predicates_of(
260        self,
261        def_id: Self::DefId,
262    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
263
264    fn explicit_super_predicates_of(
265        self,
266        def_id: Self::DefId,
267    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
268
269    fn explicit_implied_predicates_of(
270        self,
271        def_id: Self::DefId,
272    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
273
274    /// This is equivalent to computing the super-predicates of the trait for this impl
275    /// and filtering them to the outlives predicates. This is purely for performance.
276    fn impl_super_outlives(
277        self,
278        impl_def_id: Self::DefId,
279    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
280
281    fn impl_is_const(self, def_id: Self::DefId) -> bool;
282    fn fn_is_const(self, def_id: Self::DefId) -> bool;
283    fn alias_has_const_conditions(self, def_id: Self::DefId) -> bool;
284    fn const_conditions(
285        self,
286        def_id: Self::DefId,
287    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
288    fn explicit_implied_const_bounds(
289        self,
290        def_id: Self::DefId,
291    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
292
293    fn impl_self_is_guaranteed_unsized(self, def_id: Self::DefId) -> bool;
294
295    fn has_target_features(self, def_id: Self::DefId) -> bool;
296
297    fn require_lang_item(self, lang_item: TraitSolverLangItem) -> Self::DefId;
298
299    fn is_lang_item(self, def_id: Self::DefId, lang_item: TraitSolverLangItem) -> bool;
300
301    fn is_default_trait(self, def_id: Self::DefId) -> bool;
302
303    fn as_lang_item(self, def_id: Self::DefId) -> Option<TraitSolverLangItem>;
304
305    fn associated_type_def_ids(self, def_id: Self::DefId) -> impl IntoIterator<Item = Self::DefId>;
306
307    fn for_each_relevant_impl(
308        self,
309        trait_def_id: Self::DefId,
310        self_ty: Self::Ty,
311        f: impl FnMut(Self::DefId),
312    );
313
314    fn has_item_definition(self, def_id: Self::DefId) -> bool;
315
316    fn impl_specializes(self, impl_def_id: Self::DefId, victim_def_id: Self::DefId) -> bool;
317
318    fn impl_is_default(self, impl_def_id: Self::DefId) -> bool;
319
320    fn impl_trait_ref(self, impl_def_id: Self::DefId) -> ty::EarlyBinder<Self, ty::TraitRef<Self>>;
321
322    fn impl_polarity(self, impl_def_id: Self::DefId) -> ty::ImplPolarity;
323
324    fn trait_is_auto(self, trait_def_id: Self::DefId) -> bool;
325
326    fn trait_is_coinductive(self, trait_def_id: Self::DefId) -> bool;
327
328    fn trait_is_alias(self, trait_def_id: Self::DefId) -> bool;
329
330    fn trait_is_dyn_compatible(self, trait_def_id: Self::DefId) -> bool;
331
332    fn trait_is_fundamental(self, def_id: Self::DefId) -> bool;
333
334    fn trait_may_be_implemented_via_object(self, trait_def_id: Self::DefId) -> bool;
335
336    /// Returns `true` if this is an `unsafe trait`.
337    fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool;
338
339    fn is_impl_trait_in_trait(self, def_id: Self::DefId) -> bool;
340
341    fn delay_bug(self, msg: impl ToString) -> Self::ErrorGuaranteed;
342
343    fn is_general_coroutine(self, coroutine_def_id: Self::DefId) -> bool;
344    fn coroutine_is_async(self, coroutine_def_id: Self::DefId) -> bool;
345    fn coroutine_is_gen(self, coroutine_def_id: Self::DefId) -> bool;
346    fn coroutine_is_async_gen(self, coroutine_def_id: Self::DefId) -> bool;
347
348    type UnsizingParams: Deref<Target = DenseBitSet<u32>>;
349    fn unsizing_params_for_adt(self, adt_def_id: Self::DefId) -> Self::UnsizingParams;
350
351    fn anonymize_bound_vars<T: TypeFoldable<Self>>(
352        self,
353        binder: ty::Binder<Self, T>,
354    ) -> ty::Binder<Self, T>;
355
356    fn opaque_types_defined_by(self, defining_anchor: Self::LocalDefId) -> Self::LocalDefIds;
357
358    fn opaque_types_and_coroutines_defined_by(
359        self,
360        defining_anchor: Self::LocalDefId,
361    ) -> Self::LocalDefIds;
362}
363
364/// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter`
365/// that produces `T` items. You could combine them with
366/// `f(&iter.collect::<Vec<_>>())`, but this requires allocating memory for the
367/// `Vec`.
368///
369/// This trait allows for faster implementations, intended for cases where the
370/// number of items produced by the iterator is small. There is a blanket impl
371/// for `T` items, but there is also a fallible impl for `Result<T, E>` items.
372pub trait CollectAndApply<T, R>: Sized {
373    type Output;
374
375    /// Produce a result of type `Self::Output` from `iter`. The result will
376    /// typically be produced by applying `f` on the elements produced by
377    /// `iter`, though this may not happen in some impls, e.g. if an error
378    /// occurred during iteration.
379    fn collect_and_apply<I, F>(iter: I, f: F) -> Self::Output
380    where
381        I: Iterator<Item = Self>,
382        F: FnOnce(&[T]) -> R;
383}
384
385/// The blanket impl that always collects all elements and applies `f`.
386impl<T, R> CollectAndApply<T, R> for T {
387    type Output = R;
388
389    /// Equivalent to `f(&iter.collect::<Vec<_>>())`.
390    fn collect_and_apply<I, F>(mut iter: I, f: F) -> R
391    where
392        I: Iterator<Item = T>,
393        F: FnOnce(&[T]) -> R,
394    {
395        // This code is hot enough that it's worth specializing for the most
396        // common length lists, to avoid the overhead of `Vec` creation.
397
398        let Some(t0) = iter.next() else {
399            return f(&[]);
400        };
401
402        let Some(t1) = iter.next() else {
403            return f(&[t0]);
404        };
405
406        let Some(t2) = iter.next() else {
407            return f(&[t0, t1]);
408        };
409
410        let Some(t3) = iter.next() else {
411            return f(&[t0, t1, t2]);
412        };
413
414        let Some(t4) = iter.next() else {
415            return f(&[t0, t1, t2, t3]);
416        };
417
418        let Some(t5) = iter.next() else {
419            return f(&[t0, t1, t2, t3, t4]);
420        };
421
422        let Some(t6) = iter.next() else {
423            return f(&[t0, t1, t2, t3, t4, t5]);
424        };
425
426        let Some(t7) = iter.next() else {
427            return f(&[t0, t1, t2, t3, t4, t5, t6]);
428        };
429
430        let Some(t8) = iter.next() else {
431            return f(&[t0, t1, t2, t3, t4, t5, t6, t7]);
432        };
433
434        f(&[t0, t1, t2, t3, t4, t5, t6, t7, t8].into_iter().chain(iter).collect::<Vec<_>>())
435    }
436}
437
438/// A fallible impl that will fail, without calling `f`, if there are any
439/// errors during collection.
440impl<T, R, E> CollectAndApply<T, R> for Result<T, E> {
441    type Output = Result<R, E>;
442
443    /// Equivalent to `Ok(f(&iter.collect::<Result<Vec<_>>>()?))`.
444    fn collect_and_apply<I, F>(mut iter: I, f: F) -> Result<R, E>
445    where
446        I: Iterator<Item = Result<T, E>>,
447        F: FnOnce(&[T]) -> R,
448    {
449        // This code is hot enough that it's worth specializing for the most
450        // common length lists, to avoid the overhead of `Vec` creation.
451
452        let Some(t0) = iter.next() else {
453            return Ok(f(&[]));
454        };
455        let t0 = t0?;
456
457        let Some(t1) = iter.next() else {
458            return Ok(f(&[t0]));
459        };
460        let t1 = t1?;
461
462        let Some(t2) = iter.next() else {
463            return Ok(f(&[t0, t1]));
464        };
465        let t2 = t2?;
466
467        let Some(t3) = iter.next() else {
468            return Ok(f(&[t0, t1, t2]));
469        };
470        let t3 = t3?;
471
472        let Some(t4) = iter.next() else {
473            return Ok(f(&[t0, t1, t2, t3]));
474        };
475        let t4 = t4?;
476
477        let Some(t5) = iter.next() else {
478            return Ok(f(&[t0, t1, t2, t3, t4]));
479        };
480        let t5 = t5?;
481
482        let Some(t6) = iter.next() else {
483            return Ok(f(&[t0, t1, t2, t3, t4, t5]));
484        };
485        let t6 = t6?;
486
487        let Some(t7) = iter.next() else {
488            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6]));
489        };
490        let t7 = t7?;
491
492        let Some(t8) = iter.next() else {
493            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6, t7]));
494        };
495        let t8 = t8?;
496
497        Ok(f(&[Ok(t0), Ok(t1), Ok(t2), Ok(t3), Ok(t4), Ok(t5), Ok(t6), Ok(t7), Ok(t8)]
498            .into_iter()
499            .chain(iter)
500            .collect::<Result<Vec<_>, _>>()?))
501    }
502}
503
504impl<I: Interner> search_graph::Cx for I {
505    type Input = CanonicalInput<I>;
506    type Result = QueryResult<I>;
507
508    type DepNodeIndex = I::DepNodeIndex;
509    type Tracked<T: Debug + Clone> = I::Tracked<T>;
510    fn mk_tracked<T: Debug + Clone>(
511        self,
512        data: T,
513        dep_node_index: I::DepNodeIndex,
514    ) -> I::Tracked<T> {
515        I::mk_tracked(self, data, dep_node_index)
516    }
517    fn get_tracked<T: Debug + Clone>(self, tracked: &I::Tracked<T>) -> T {
518        I::get_tracked(self, tracked)
519    }
520    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, I::DepNodeIndex) {
521        I::with_cached_task(self, task)
522    }
523    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R {
524        I::with_global_cache(self, f)
525    }
526    fn evaluation_is_concurrent(&self) -> bool {
527        self.evaluation_is_concurrent()
528    }
529}