rustc_type_ir/
interner.rs

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