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