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 closure_is_const(self, def_id: Self::ClosureId) -> bool;
312    fn alias_has_const_conditions(self, def_id: Self::DefId) -> bool;
313    fn const_conditions(
314        self,
315        def_id: Self::DefId,
316    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
317    fn explicit_implied_const_bounds(
318        self,
319        def_id: Self::DefId,
320    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
321
322    fn impl_self_is_guaranteed_unsized(self, def_id: Self::ImplId) -> bool;
323
324    fn has_target_features(self, def_id: Self::FunctionId) -> bool;
325
326    fn require_lang_item(self, lang_item: SolverLangItem) -> Self::DefId;
327
328    fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> Self::TraitId;
329
330    fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> Self::AdtId;
331
332    fn is_lang_item(self, def_id: Self::DefId, lang_item: SolverLangItem) -> bool;
333
334    fn is_trait_lang_item(self, def_id: Self::TraitId, lang_item: SolverTraitLangItem) -> bool;
335
336    fn is_adt_lang_item(self, def_id: Self::AdtId, lang_item: SolverAdtLangItem) -> bool;
337
338    fn is_default_trait(self, def_id: Self::TraitId) -> bool;
339
340    fn is_sizedness_trait(self, def_id: Self::TraitId) -> bool;
341
342    fn as_lang_item(self, def_id: Self::DefId) -> Option<SolverLangItem>;
343
344    fn as_trait_lang_item(self, def_id: Self::TraitId) -> Option<SolverTraitLangItem>;
345
346    fn as_adt_lang_item(self, def_id: Self::AdtId) -> Option<SolverAdtLangItem>;
347
348    fn associated_type_def_ids(
349        self,
350        def_id: Self::TraitId,
351    ) -> impl IntoIterator<Item = Self::DefId>;
352
353    fn for_each_relevant_impl(
354        self,
355        trait_def_id: Self::TraitId,
356        self_ty: Self::Ty,
357        f: impl FnMut(Self::ImplId),
358    );
359    fn for_each_blanket_impl(self, trait_def_id: Self::TraitId, f: impl FnMut(Self::ImplId));
360
361    fn has_item_definition(self, def_id: Self::DefId) -> bool;
362
363    fn impl_specializes(self, impl_def_id: Self::ImplId, victim_def_id: Self::ImplId) -> bool;
364
365    fn impl_is_default(self, impl_def_id: Self::ImplId) -> bool;
366
367    fn impl_trait_ref(self, impl_def_id: Self::ImplId)
368    -> ty::EarlyBinder<Self, ty::TraitRef<Self>>;
369
370    fn impl_polarity(self, impl_def_id: Self::ImplId) -> ty::ImplPolarity;
371
372    fn trait_is_auto(self, trait_def_id: Self::TraitId) -> bool;
373
374    fn trait_is_coinductive(self, trait_def_id: Self::TraitId) -> bool;
375
376    fn trait_is_alias(self, trait_def_id: Self::TraitId) -> bool;
377
378    fn trait_is_dyn_compatible(self, trait_def_id: Self::TraitId) -> bool;
379
380    fn trait_is_fundamental(self, def_id: Self::TraitId) -> bool;
381
382    /// Returns `true` if this is an `unsafe trait`.
383    fn trait_is_unsafe(self, trait_def_id: Self::TraitId) -> bool;
384
385    fn is_impl_trait_in_trait(self, def_id: Self::DefId) -> bool;
386
387    fn delay_bug(self, msg: impl ToString) -> Self::ErrorGuaranteed;
388
389    fn is_general_coroutine(self, coroutine_def_id: Self::CoroutineId) -> bool;
390    fn coroutine_is_async(self, coroutine_def_id: Self::CoroutineId) -> bool;
391    fn coroutine_is_gen(self, coroutine_def_id: Self::CoroutineId) -> bool;
392    fn coroutine_is_async_gen(self, coroutine_def_id: Self::CoroutineId) -> bool;
393
394    type UnsizingParams: Deref<Target = DenseBitSet<u32>>;
395    fn unsizing_params_for_adt(self, adt_def_id: Self::AdtId) -> Self::UnsizingParams;
396
397    fn anonymize_bound_vars<T: TypeFoldable<Self>>(
398        self,
399        binder: ty::Binder<Self, T>,
400    ) -> ty::Binder<Self, T>;
401
402    fn opaque_types_defined_by(self, defining_anchor: Self::LocalDefId) -> Self::LocalDefIds;
403
404    fn opaque_types_and_coroutines_defined_by(
405        self,
406        defining_anchor: Self::LocalDefId,
407    ) -> Self::LocalDefIds;
408
409    type Probe: Debug + Hash + Eq + Borrow<inspect::Probe<Self>>;
410    fn mk_probe(self, probe: inspect::Probe<Self>) -> Self::Probe;
411    fn evaluate_root_goal_for_proof_tree_raw(
412        self,
413        canonical_goal: CanonicalInput<Self>,
414    ) -> (QueryResult<Self>, Self::Probe);
415
416    fn item_name(self, item_index: Self::DefId) -> Self::Symbol;
417}
418
419/// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter`
420/// that produces `T` items. You could combine them with
421/// `f(&iter.collect::<Vec<_>>())`, but this requires allocating memory for the
422/// `Vec`.
423///
424/// This trait allows for faster implementations, intended for cases where the
425/// number of items produced by the iterator is small. There is a blanket impl
426/// for `T` items, but there is also a fallible impl for `Result<T, E>` items.
427pub trait CollectAndApply<T, R>: Sized {
428    type Output;
429
430    /// Produce a result of type `Self::Output` from `iter`. The result will
431    /// typically be produced by applying `f` on the elements produced by
432    /// `iter`, though this may not happen in some impls, e.g. if an error
433    /// occurred during iteration.
434    fn collect_and_apply<I, F>(iter: I, f: F) -> Self::Output
435    where
436        I: Iterator<Item = Self>,
437        F: FnOnce(&[T]) -> R;
438}
439
440/// The blanket impl that always collects all elements and applies `f`.
441impl<T, R> CollectAndApply<T, R> for T {
442    type Output = R;
443
444    /// Equivalent to `f(&iter.collect::<Vec<_>>())`.
445    fn collect_and_apply<I, F>(mut iter: I, f: F) -> R
446    where
447        I: Iterator<Item = T>,
448        F: FnOnce(&[T]) -> R,
449    {
450        // This code is hot enough that it's worth specializing for the most
451        // common length lists, to avoid the overhead of `Vec` creation.
452
453        let Some(t0) = iter.next() else {
454            return f(&[]);
455        };
456
457        let Some(t1) = iter.next() else {
458            return f(&[t0]);
459        };
460
461        let Some(t2) = iter.next() else {
462            return f(&[t0, t1]);
463        };
464
465        let Some(t3) = iter.next() else {
466            return f(&[t0, t1, t2]);
467        };
468
469        let Some(t4) = iter.next() else {
470            return f(&[t0, t1, t2, t3]);
471        };
472
473        let Some(t5) = iter.next() else {
474            return f(&[t0, t1, t2, t3, t4]);
475        };
476
477        let Some(t6) = iter.next() else {
478            return f(&[t0, t1, t2, t3, t4, t5]);
479        };
480
481        let Some(t7) = iter.next() else {
482            return f(&[t0, t1, t2, t3, t4, t5, t6]);
483        };
484
485        let Some(t8) = iter.next() else {
486            return f(&[t0, t1, t2, t3, t4, t5, t6, t7]);
487        };
488
489        f(&[t0, t1, t2, t3, t4, t5, t6, t7, t8].into_iter().chain(iter).collect::<Vec<_>>())
490    }
491}
492
493/// A fallible impl that will fail, without calling `f`, if there are any
494/// errors during collection.
495impl<T, R, E> CollectAndApply<T, R> for Result<T, E> {
496    type Output = Result<R, E>;
497
498    /// Equivalent to `Ok(f(&iter.collect::<Result<Vec<_>>>()?))`.
499    fn collect_and_apply<I, F>(mut iter: I, f: F) -> Result<R, E>
500    where
501        I: Iterator<Item = Result<T, E>>,
502        F: FnOnce(&[T]) -> R,
503    {
504        // This code is hot enough that it's worth specializing for the most
505        // common length lists, to avoid the overhead of `Vec` creation.
506
507        let Some(t0) = iter.next() else {
508            return Ok(f(&[]));
509        };
510        let t0 = t0?;
511
512        let Some(t1) = iter.next() else {
513            return Ok(f(&[t0]));
514        };
515        let t1 = t1?;
516
517        let Some(t2) = iter.next() else {
518            return Ok(f(&[t0, t1]));
519        };
520        let t2 = t2?;
521
522        let Some(t3) = iter.next() else {
523            return Ok(f(&[t0, t1, t2]));
524        };
525        let t3 = t3?;
526
527        let Some(t4) = iter.next() else {
528            return Ok(f(&[t0, t1, t2, t3]));
529        };
530        let t4 = t4?;
531
532        let Some(t5) = iter.next() else {
533            return Ok(f(&[t0, t1, t2, t3, t4]));
534        };
535        let t5 = t5?;
536
537        let Some(t6) = iter.next() else {
538            return Ok(f(&[t0, t1, t2, t3, t4, t5]));
539        };
540        let t6 = t6?;
541
542        let Some(t7) = iter.next() else {
543            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6]));
544        };
545        let t7 = t7?;
546
547        let Some(t8) = iter.next() else {
548            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6, t7]));
549        };
550        let t8 = t8?;
551
552        Ok(f(&[Ok(t0), Ok(t1), Ok(t2), Ok(t3), Ok(t4), Ok(t5), Ok(t6), Ok(t7), Ok(t8)]
553            .into_iter()
554            .chain(iter)
555            .collect::<Result<Vec<_>, _>>()?))
556    }
557}
558
559impl<I: Interner> search_graph::Cx for I {
560    type Input = CanonicalInput<I>;
561    type Result = QueryResult<I>;
562    type AmbiguityInfo = Certainty;
563
564    type DepNodeIndex = I::DepNodeIndex;
565    type Tracked<T: Debug + Clone> = I::Tracked<T>;
566    fn mk_tracked<T: Debug + Clone>(
567        self,
568        data: T,
569        dep_node_index: I::DepNodeIndex,
570    ) -> I::Tracked<T> {
571        I::mk_tracked(self, data, dep_node_index)
572    }
573    fn get_tracked<T: Debug + Clone>(self, tracked: &I::Tracked<T>) -> T {
574        I::get_tracked(self, tracked)
575    }
576    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, I::DepNodeIndex) {
577        I::with_cached_task(self, task)
578    }
579    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R {
580        I::with_global_cache(self, f)
581    }
582    fn assert_evaluation_is_concurrent(&self) {
583        self.assert_evaluation_is_concurrent()
584    }
585}