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