Skip to main content

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