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 + Debug + Hash + Eq + SliceLike<Item = Self::BoundVarKind> + Default;
65    type BoundVarKind: Copy + Debug + Hash + Eq;
66
67    type PredefinedOpaques: Copy
68        + Debug
69        + Hash
70        + Eq
71        + TypeFoldable<Self>
72        + SliceLike<Item = (ty::OpaqueTypeKey<Self>, Self::Ty)>;
73    fn mk_predefined_opaques_in_body(
74        self,
75        data: &[(ty::OpaqueTypeKey<Self>, Self::Ty)],
76    ) -> Self::PredefinedOpaques;
77
78    type LocalDefIds: Copy
79        + Debug
80        + Hash
81        + Default
82        + Eq
83        + TypeVisitable<Self>
84        + SliceLike<Item = Self::LocalDefId>;
85
86    type CanonicalVarKinds: Copy
87        + Debug
88        + Hash
89        + Eq
90        + SliceLike<Item = ty::CanonicalVarKind<Self>>
91        + Default;
92    fn mk_canonical_var_kinds(
93        self,
94        kinds: &[ty::CanonicalVarKind<Self>],
95    ) -> Self::CanonicalVarKinds;
96
97    type ExternalConstraints: Copy
98        + Debug
99        + Hash
100        + Eq
101        + TypeFoldable<Self>
102        + Deref<Target = ExternalConstraintsData<Self>>;
103    fn mk_external_constraints(
104        self,
105        data: ExternalConstraintsData<Self>,
106    ) -> Self::ExternalConstraints;
107
108    type DepNodeIndex;
109    type Tracked<T: Debug + Clone>: Debug;
110    fn mk_tracked<T: Debug + Clone>(
111        self,
112        data: T,
113        dep_node: Self::DepNodeIndex,
114    ) -> Self::Tracked<T>;
115    fn get_tracked<T: Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T;
116    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, Self::DepNodeIndex);
117
118    // Kinds of tys
119    type Ty: Ty<Self>;
120    type Tys: Tys<Self>;
121    type FnInputTys: Copy + Debug + Hash + Eq + SliceLike<Item = Self::Ty> + TypeVisitable<Self>;
122    type ParamTy: ParamLike;
123    type BoundTy: BoundVarLike<Self>;
124    type PlaceholderTy: PlaceholderLike<Self, Bound = Self::BoundTy>;
125    type Symbol: Copy + Hash + PartialEq + Eq + Debug;
126
127    // Things stored inside of tys
128    type ErrorGuaranteed: Copy + Debug + Hash + Eq;
129    type BoundExistentialPredicates: BoundExistentialPredicates<Self>;
130    type AllocId: Copy + Debug + Hash + Eq;
131    type Pat: Copy
132        + Debug
133        + Hash
134        + Eq
135        + Debug
136        + Relate<Self>
137        + Flags
138        + IntoKind<Kind = ty::PatternKind<Self>>;
139    type PatList: Copy
140        + Debug
141        + Hash
142        + Default
143        + Eq
144        + TypeVisitable<Self>
145        + SliceLike<Item = Self::Pat>;
146    type Safety: Safety<Self>;
147    type Abi: Abi<Self>;
148
149    // Kinds of consts
150    type Const: Const<Self>;
151    type ParamConst: Copy + Debug + Hash + Eq + ParamLike;
152    type BoundConst: BoundVarLike<Self>;
153    type PlaceholderConst: PlaceholderConst<Self>;
154    type ValueConst: ValueConst<Self>;
155    type ExprConst: ExprConst<Self>;
156    type ValTree: ValTree<Self>;
157    type ScalarInt: Copy + Debug + Hash + Eq;
158
159    // Kinds of regions
160    type Region: Region<Self>;
161    type EarlyParamRegion: ParamLike;
162    type LateParamRegion: Copy + Debug + Hash + Eq;
163    type BoundRegion: BoundVarLike<Self>;
164    type PlaceholderRegion: PlaceholderLike<Self, Bound = Self::BoundRegion>;
165
166    type RegionAssumptions: Copy
167        + Debug
168        + Hash
169        + Eq
170        + SliceLike<Item = ty::OutlivesPredicate<Self, Self::GenericArg>>
171        + TypeFoldable<Self>;
172
173    // Predicates
174    type ParamEnv: ParamEnv<Self>;
175    type Predicate: Predicate<Self>;
176    type Clause: Clause<Self>;
177    type Clauses: Clauses<Self>;
178
179    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R;
180
181    fn canonical_param_env_cache_get_or_insert<R>(
182        self,
183        param_env: Self::ParamEnv,
184        f: impl FnOnce() -> CanonicalParamEnvCacheEntry<Self>,
185        from_entry: impl FnOnce(&CanonicalParamEnvCacheEntry<Self>) -> R,
186    ) -> R;
187
188    /// Useful for testing. If a cache entry is replaced, this should
189    /// (in theory) only happen when concurrent.
190    fn assert_evaluation_is_concurrent(&self);
191
192    fn expand_abstract_consts<T: TypeFoldable<Self>>(self, t: T) -> T;
193
194    type GenericsOf: GenericsOf<Self>;
195    fn generics_of(self, def_id: Self::DefId) -> Self::GenericsOf;
196
197    type VariancesOf: Copy + Debug + SliceLike<Item = ty::Variance>;
198    fn variances_of(self, def_id: Self::DefId) -> Self::VariancesOf;
199
200    fn opt_alias_variances(
201        self,
202        kind: impl Into<ty::AliasTermKind>,
203        def_id: Self::DefId,
204    ) -> Option<Self::VariancesOf>;
205
206    fn type_of(self, def_id: Self::DefId) -> ty::EarlyBinder<Self, Self::Ty>;
207    fn type_of_opaque_hir_typeck(self, def_id: Self::LocalDefId)
208    -> ty::EarlyBinder<Self, Self::Ty>;
209    fn const_of_item(self, def_id: Self::DefId) -> ty::EarlyBinder<Self, Self::Const>;
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    fn trait_may_be_implemented_via_object(self, trait_def_id: Self::TraitId) -> bool;
382
383    /// Returns `true` if this is an `unsafe trait`.
384    fn trait_is_unsafe(self, trait_def_id: Self::TraitId) -> bool;
385
386    fn is_impl_trait_in_trait(self, def_id: Self::DefId) -> bool;
387
388    fn delay_bug(self, msg: impl ToString) -> Self::ErrorGuaranteed;
389
390    fn is_general_coroutine(self, coroutine_def_id: Self::CoroutineId) -> bool;
391    fn coroutine_is_async(self, coroutine_def_id: Self::CoroutineId) -> bool;
392    fn coroutine_is_gen(self, coroutine_def_id: Self::CoroutineId) -> bool;
393    fn coroutine_is_async_gen(self, coroutine_def_id: Self::CoroutineId) -> bool;
394
395    type UnsizingParams: Deref<Target = DenseBitSet<u32>>;
396    fn unsizing_params_for_adt(self, adt_def_id: Self::AdtId) -> Self::UnsizingParams;
397
398    fn anonymize_bound_vars<T: TypeFoldable<Self>>(
399        self,
400        binder: ty::Binder<Self, T>,
401    ) -> ty::Binder<Self, T>;
402
403    fn opaque_types_defined_by(self, defining_anchor: Self::LocalDefId) -> Self::LocalDefIds;
404
405    fn opaque_types_and_coroutines_defined_by(
406        self,
407        defining_anchor: Self::LocalDefId,
408    ) -> Self::LocalDefIds;
409
410    type Probe: Debug + Hash + Eq + Borrow<inspect::Probe<Self>>;
411    fn mk_probe(self, probe: inspect::Probe<Self>) -> Self::Probe;
412    fn evaluate_root_goal_for_proof_tree_raw(
413        self,
414        canonical_goal: CanonicalInput<Self>,
415    ) -> (QueryResult<Self>, Self::Probe);
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}