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: Copy + Debug + Hash + Eq;
157
158    // Kinds of regions
159    type Region: Region<Self>;
160    type EarlyParamRegion: ParamLike;
161    type LateParamRegion: Copy + Debug + Hash + Eq;
162    type BoundRegion: BoundVarLike<Self>;
163    type PlaceholderRegion: PlaceholderLike<Self, Bound = Self::BoundRegion>;
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
210    type AdtDef: AdtDef<Self>;
211    fn adt_def(self, adt_def_id: Self::AdtId) -> Self::AdtDef;
212
213    fn alias_ty_kind(self, alias: ty::AliasTy<Self>) -> ty::AliasTyKind;
214
215    fn alias_term_kind(self, alias: ty::AliasTerm<Self>) -> ty::AliasTermKind;
216
217    fn trait_ref_and_own_args_for_alias(
218        self,
219        def_id: Self::DefId,
220        args: Self::GenericArgs,
221    ) -> (ty::TraitRef<Self>, Self::GenericArgsSlice);
222
223    fn mk_args(self, args: &[Self::GenericArg]) -> Self::GenericArgs;
224
225    fn mk_args_from_iter<I, T>(self, args: I) -> T::Output
226    where
227        I: Iterator<Item = T>,
228        T: CollectAndApply<Self::GenericArg, Self::GenericArgs>;
229
230    fn check_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs) -> bool;
231
232    fn debug_assert_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs);
233
234    /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection`
235    /// are compatible with the `DefId`.
236    fn debug_assert_existential_args_compatible(self, def_id: Self::DefId, args: Self::GenericArgs);
237
238    fn mk_type_list_from_iter<I, T>(self, args: I) -> T::Output
239    where
240        I: Iterator<Item = T>,
241        T: CollectAndApply<Self::Ty, Self::Tys>;
242
243    fn parent(self, def_id: Self::DefId) -> Self::DefId;
244
245    fn recursion_limit(self) -> usize;
246
247    type Features: Features<Self>;
248    fn features(self) -> Self::Features;
249
250    fn coroutine_hidden_types(
251        self,
252        def_id: Self::CoroutineId,
253    ) -> ty::EarlyBinder<Self, ty::Binder<Self, ty::CoroutineWitnessTypes<Self>>>;
254
255    fn fn_sig(
256        self,
257        def_id: Self::FunctionId,
258    ) -> ty::EarlyBinder<Self, ty::Binder<Self, ty::FnSig<Self>>>;
259
260    fn coroutine_movability(self, def_id: Self::CoroutineId) -> Movability;
261
262    fn coroutine_for_closure(self, def_id: Self::CoroutineClosureId) -> Self::CoroutineId;
263
264    fn generics_require_sized_self(self, def_id: Self::DefId) -> bool;
265
266    fn item_bounds(
267        self,
268        def_id: Self::DefId,
269    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
270
271    fn item_self_bounds(
272        self,
273        def_id: Self::DefId,
274    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
275
276    fn item_non_self_bounds(
277        self,
278        def_id: Self::DefId,
279    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
280
281    fn predicates_of(
282        self,
283        def_id: Self::DefId,
284    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
285
286    fn own_predicates_of(
287        self,
288        def_id: Self::DefId,
289    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
290
291    fn explicit_super_predicates_of(
292        self,
293        def_id: Self::TraitId,
294    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
295
296    fn explicit_implied_predicates_of(
297        self,
298        def_id: Self::DefId,
299    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
300
301    /// This is equivalent to computing the super-predicates of the trait for this impl
302    /// and filtering them to the outlives predicates. This is purely for performance.
303    fn impl_super_outlives(
304        self,
305        impl_def_id: Self::ImplId,
306    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
307
308    fn impl_is_const(self, def_id: Self::ImplId) -> bool;
309    fn fn_is_const(self, def_id: Self::FunctionId) -> bool;
310    fn alias_has_const_conditions(self, def_id: Self::DefId) -> bool;
311    fn const_conditions(
312        self,
313        def_id: Self::DefId,
314    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
315    fn explicit_implied_const_bounds(
316        self,
317        def_id: Self::DefId,
318    ) -> ty::EarlyBinder<Self, impl IntoIterator<Item = ty::Binder<Self, ty::TraitRef<Self>>>>;
319
320    fn impl_self_is_guaranteed_unsized(self, def_id: Self::ImplId) -> bool;
321
322    fn has_target_features(self, def_id: Self::FunctionId) -> bool;
323
324    fn require_lang_item(self, lang_item: SolverLangItem) -> Self::DefId;
325
326    fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> Self::TraitId;
327
328    fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> Self::AdtId;
329
330    fn is_lang_item(self, def_id: Self::DefId, lang_item: SolverLangItem) -> bool;
331
332    fn is_trait_lang_item(self, def_id: Self::TraitId, lang_item: SolverTraitLangItem) -> bool;
333
334    fn is_adt_lang_item(self, def_id: Self::AdtId, lang_item: SolverAdtLangItem) -> bool;
335
336    fn is_default_trait(self, def_id: Self::TraitId) -> bool;
337
338    fn is_sizedness_trait(self, def_id: Self::TraitId) -> bool;
339
340    fn as_lang_item(self, def_id: Self::DefId) -> Option<SolverLangItem>;
341
342    fn as_trait_lang_item(self, def_id: Self::TraitId) -> Option<SolverTraitLangItem>;
343
344    fn as_adt_lang_item(self, def_id: Self::AdtId) -> Option<SolverAdtLangItem>;
345
346    fn associated_type_def_ids(
347        self,
348        def_id: Self::TraitId,
349    ) -> impl IntoIterator<Item = Self::DefId>;
350
351    fn for_each_relevant_impl(
352        self,
353        trait_def_id: Self::TraitId,
354        self_ty: Self::Ty,
355        f: impl FnMut(Self::ImplId),
356    );
357    fn for_each_blanket_impl(self, trait_def_id: Self::TraitId, f: impl FnMut(Self::ImplId));
358
359    fn has_item_definition(self, def_id: Self::DefId) -> bool;
360
361    fn impl_specializes(self, impl_def_id: Self::ImplId, victim_def_id: Self::ImplId) -> bool;
362
363    fn impl_is_default(self, impl_def_id: Self::ImplId) -> bool;
364
365    fn impl_trait_ref(self, impl_def_id: Self::ImplId)
366    -> ty::EarlyBinder<Self, ty::TraitRef<Self>>;
367
368    fn impl_polarity(self, impl_def_id: Self::ImplId) -> ty::ImplPolarity;
369
370    fn trait_is_auto(self, trait_def_id: Self::TraitId) -> bool;
371
372    fn trait_is_coinductive(self, trait_def_id: Self::TraitId) -> bool;
373
374    fn trait_is_alias(self, trait_def_id: Self::TraitId) -> bool;
375
376    fn trait_is_dyn_compatible(self, trait_def_id: Self::TraitId) -> bool;
377
378    fn trait_is_fundamental(self, def_id: Self::TraitId) -> bool;
379
380    fn trait_may_be_implemented_via_object(self, trait_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
417/// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter`
418/// that produces `T` items. You could combine them with
419/// `f(&iter.collect::<Vec<_>>())`, but this requires allocating memory for the
420/// `Vec`.
421///
422/// This trait allows for faster implementations, intended for cases where the
423/// number of items produced by the iterator is small. There is a blanket impl
424/// for `T` items, but there is also a fallible impl for `Result<T, E>` items.
425pub trait CollectAndApply<T, R>: Sized {
426    type Output;
427
428    /// Produce a result of type `Self::Output` from `iter`. The result will
429    /// typically be produced by applying `f` on the elements produced by
430    /// `iter`, though this may not happen in some impls, e.g. if an error
431    /// occurred during iteration.
432    fn collect_and_apply<I, F>(iter: I, f: F) -> Self::Output
433    where
434        I: Iterator<Item = Self>,
435        F: FnOnce(&[T]) -> R;
436}
437
438/// The blanket impl that always collects all elements and applies `f`.
439impl<T, R> CollectAndApply<T, R> for T {
440    type Output = R;
441
442    /// Equivalent to `f(&iter.collect::<Vec<_>>())`.
443    fn collect_and_apply<I, F>(mut iter: I, f: F) -> R
444    where
445        I: Iterator<Item = T>,
446        F: FnOnce(&[T]) -> R,
447    {
448        // This code is hot enough that it's worth specializing for the most
449        // common length lists, to avoid the overhead of `Vec` creation.
450
451        let Some(t0) = iter.next() else {
452            return f(&[]);
453        };
454
455        let Some(t1) = iter.next() else {
456            return f(&[t0]);
457        };
458
459        let Some(t2) = iter.next() else {
460            return f(&[t0, t1]);
461        };
462
463        let Some(t3) = iter.next() else {
464            return f(&[t0, t1, t2]);
465        };
466
467        let Some(t4) = iter.next() else {
468            return f(&[t0, t1, t2, t3]);
469        };
470
471        let Some(t5) = iter.next() else {
472            return f(&[t0, t1, t2, t3, t4]);
473        };
474
475        let Some(t6) = iter.next() else {
476            return f(&[t0, t1, t2, t3, t4, t5]);
477        };
478
479        let Some(t7) = iter.next() else {
480            return f(&[t0, t1, t2, t3, t4, t5, t6]);
481        };
482
483        let Some(t8) = iter.next() else {
484            return f(&[t0, t1, t2, t3, t4, t5, t6, t7]);
485        };
486
487        f(&[t0, t1, t2, t3, t4, t5, t6, t7, t8].into_iter().chain(iter).collect::<Vec<_>>())
488    }
489}
490
491/// A fallible impl that will fail, without calling `f`, if there are any
492/// errors during collection.
493impl<T, R, E> CollectAndApply<T, R> for Result<T, E> {
494    type Output = Result<R, E>;
495
496    /// Equivalent to `Ok(f(&iter.collect::<Result<Vec<_>>>()?))`.
497    fn collect_and_apply<I, F>(mut iter: I, f: F) -> Result<R, E>
498    where
499        I: Iterator<Item = Result<T, E>>,
500        F: FnOnce(&[T]) -> R,
501    {
502        // This code is hot enough that it's worth specializing for the most
503        // common length lists, to avoid the overhead of `Vec` creation.
504
505        let Some(t0) = iter.next() else {
506            return Ok(f(&[]));
507        };
508        let t0 = t0?;
509
510        let Some(t1) = iter.next() else {
511            return Ok(f(&[t0]));
512        };
513        let t1 = t1?;
514
515        let Some(t2) = iter.next() else {
516            return Ok(f(&[t0, t1]));
517        };
518        let t2 = t2?;
519
520        let Some(t3) = iter.next() else {
521            return Ok(f(&[t0, t1, t2]));
522        };
523        let t3 = t3?;
524
525        let Some(t4) = iter.next() else {
526            return Ok(f(&[t0, t1, t2, t3]));
527        };
528        let t4 = t4?;
529
530        let Some(t5) = iter.next() else {
531            return Ok(f(&[t0, t1, t2, t3, t4]));
532        };
533        let t5 = t5?;
534
535        let Some(t6) = iter.next() else {
536            return Ok(f(&[t0, t1, t2, t3, t4, t5]));
537        };
538        let t6 = t6?;
539
540        let Some(t7) = iter.next() else {
541            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6]));
542        };
543        let t7 = t7?;
544
545        let Some(t8) = iter.next() else {
546            return Ok(f(&[t0, t1, t2, t3, t4, t5, t6, t7]));
547        };
548        let t8 = t8?;
549
550        Ok(f(&[Ok(t0), Ok(t1), Ok(t2), Ok(t3), Ok(t4), Ok(t5), Ok(t6), Ok(t7), Ok(t8)]
551            .into_iter()
552            .chain(iter)
553            .collect::<Result<Vec<_>, _>>()?))
554    }
555}
556
557impl<I: Interner> search_graph::Cx for I {
558    type Input = CanonicalInput<I>;
559    type Result = QueryResult<I>;
560    type AmbiguityInfo = Certainty;
561
562    type DepNodeIndex = I::DepNodeIndex;
563    type Tracked<T: Debug + Clone> = I::Tracked<T>;
564    fn mk_tracked<T: Debug + Clone>(
565        self,
566        data: T,
567        dep_node_index: I::DepNodeIndex,
568    ) -> I::Tracked<T> {
569        I::mk_tracked(self, data, dep_node_index)
570    }
571    fn get_tracked<T: Debug + Clone>(self, tracked: &I::Tracked<T>) -> T {
572        I::get_tracked(self, tracked)
573    }
574    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, I::DepNodeIndex) {
575        I::with_cached_task(self, task)
576    }
577    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R {
578        I::with_global_cache(self, f)
579    }
580    fn assert_evaluation_is_concurrent(&self) {
581        self.assert_evaluation_is_concurrent()
582    }
583}